如何解决测试是否在挂钩中调用了窗口函数
我有一个需要在react钩子中模拟的函数:window.analytics.identify
并测试它是否被调用
function useNiceHook(data) {
useEffect(() => {
...
window.analytics.identify(
...
},[data])
}
export { useNiceHook }
我正试图像这样
windowSpy.mockImplementation(() => ({
analytics: {
identify: jest.fn(),},}))
然后测试:
renderHook(() => useNiceHook(data))
expect(window.analytics.identify).toBeCalled()
但是我目前测试失败:
Error: expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0
解决方法
单元测试解决方案:
index.js
:
import { useEffect } from 'react';
function useNiceHook(data) {
useEffect(() => {
window.analytics.identify();
},[data]);
}
export { useNiceHook };
index.test.js
:
import { useNiceHook } from './';
import { renderHook } from '@testing-library/react-hooks';
describe('63401335',() => {
it('should pass',() => {
const mAnalytics = {
identify: jest.fn(),};
Object.defineProperty(window,'analytics',{
value: mAnalytics,});
const data = {};
renderHook(() => useNiceHook(data));
expect(mAnalytics.identify).toBeCalled();
});
});
具有覆盖率报告的单元测试结果:
PASS src/stackoverflow/63401335/index.test.js
63401335
✓ should pass (24ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed,1 total
Tests: 1 passed,1 total
Snapshots: 0 total
Time: 5.13s,estimated 13s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63401335
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。