我有一个使用firebase.analytics()的组件,我尝试对其进行模拟。
//__mocks__/firebase/app.mocks.ts
export const analytics = jest.fn();
尝试在第二行中这样调用它时出现错误:
firebase.initializeApp(clientCredentials);
firebase.analytics();
错误是TypeError:_app.default.analytics不是函数
用玩笑来模拟这些:
jest.mock('firebase/app');
jest.mock('firebase/analytics');
我应该做更多的事情吗?
答案 0 :(得分:1)
这是仅使用jest.mock(moduleName, factory, options)方法而不创建A a = 1;
目录的示例。
__mocks__
:
index.ts
import firebase from 'firebase';
function main() {
const clientCredentials = {};
firebase.initializeApp(clientCredentials);
firebase.analytics();
}
export { main };
:
index.test.ts
单元测试结果:
import { main } from './';
import firebase from 'firebase';
jest.mock('firebase', () => {
return { initializeApp: jest.fn(), analytics: jest.fn() };
});
describe('63008620', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should pass', () => {
main();
expect(firebase.initializeApp).toBeCalledWith({});
expect(firebase.analytics).toBeCalledTimes(1);
});
});