Reputation: 796
I cannot seem to make mock work properly.
a bit of context :
"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"
storage.ts contains a method getOsTmpDir
.
moduleA.ts is consuming storage.ts
in moduleA.spec.ts :
jest.mock('./storage', () => ({
getOsTmpDir: jest.fn().mockImplementation(() => '/tmp'),
}));
printing (in console.log(getOsTmpDir());
give undefined
other things I've tried :
getOsTmpDir: jest.fn(() => '/tmp')
getOsTmpDir: jest.fn().mockReturnValue('/tmp')
but nothing seems to help. what am I missing?
Edit : I've found the issue. I didn't notice that all mocks were resetting before each test, and since I've defined the mocks at the top of the file (once), the mocks were terminated right before running any test
beforeEach(async () => {
jest.resetAllMocks(); <----
....
}
Upvotes: 4
Views: 1730
Reputation: 668
How are you exporting/importing that method? This is what it should look like when mocking an exported function:
Defining the "real" function:
~fileA.ts
...
export function what() {
console.log('A');
}
...
Test:
~test.ts
...
import { what } from './fileA';
jest.mock('./fileA', () => ({
what: jest.fn().mockImplementation(() => console.log('B')),
}));
describe('mocks', () => {
it('should work', () => {
what();
});
});
$ jest test.ts
...
console.log test.ts:9
B
And you should see that the test called the mock implementation of what
and logged a B.
Upvotes: 1