我有一个需要在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
答案 0 :(得分:1)
单元测试解决方案:
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