Reputation: 55
I have a component that use firebase.analytics() and I try to mock it.
//__mocks__/firebase/app.mocks.ts
export const analytics = jest.fn();
And I get an error when is trying to call it like this on the second line:
firebase.initializeApp(clientCredentials);
firebase.analytics();
The error is TypeError: _app.default.analytics is not a function
Used jest to mock these like this:
jest.mock('firebase/app');
jest.mock('firebase/analytics');
I should do something more?
Upvotes: 1
Views: 2438
Reputation: 102207
Here is an example only using jest.mock(moduleName, factory, options) method without creating __mocks__
directory.
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);
});
});
unit test result:
PASS stackoverflow/63008620/index.test.ts (14.665s)
63008620
✓ should pass (7ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 16.565s
Upvotes: 2