Reputation: 307
I'm doing my best to follow along with the docs for jest and I'm also trying my best to learn on my own. I'm having an issue while following the docs on the official jest website. I'm on the mocking modules section. It had to do with axios but I kept getting the error in typescript that that mockImplementation is not a property on (whatever the mock is)
I've tried looking around to see if it's an issue with my config but I can't figure it out.
// foo.ts
export default function() {
// some implementation;
};
test.ts
import foo from '../src/foo';
// test.js
jest.mock('../src/foo'); // this happens automatically with automocking
foo.mockImplementation(() => 42);
foo();
console.log(foo())
Here is the error I get on mockImplementatin
Property 'mockImplementation' does not exist on type '() => void'.ts(2339)
All I'm doing is following the docs. I've had no issue until I got to section.
Upvotes: 2
Views: 2484
Reputation: 45810
This foo.ts
:
export default function() {
return 1;
};
...can be mocked like this:
import * as fooModule from '../src/foo';
jest.mock('../src/foo');
const mockedFooModule = fooModule as jest.Mocked<typeof fooModule>;
const foo = mockedFooModule.default;
test('foo', () => {
foo.mockImplementation(() => 2);
expect(foo()).toBe(2); // Success!
})
The typing for Jest
provides jest.Mocked
which can be used to generate the correct typing for an auto-mocked version of a module.
In this case the module has a single default
export so this line:
const foo = mockedFooModule.default
...will assign foo
to the correctly typed mocked default export.
Upvotes: 5