Reputation: 738
I'm trying to mock a function of an object with Jest and Typescript and it just does not work. Here is a short version of what I have:
// myModule.ts
export const Foo = {
doSomething: () => {
// ... does something
console.log('original implementation');
}
}
Then in my test:
jest.mock('.myModule.ts', () => {
return {
Foo: {
doSomething: jest.fn().mockImplementation(() => {
console.log('mock implementation')
})
}
}
})
// .. further down in the test
Foo.doSomething();
Shouldn't the console.log('mock implementation')
be called when I call Foo.doSomething()
? It doesn't error and it's not calling the original implementation anymore, but it's also not calling my mockImplementation.
Upvotes: 0
Views: 245
Reputation: 7298
After switching to jest 26.6, I found that none of these worked outside of tests (had been doing it directly below my imports, outside of any describe
or it
call). If I wanted any kind of mock implementation, I had to set it in the test, or in a beforeEach
. If anyone can supply a link to the documentation on this, I'd be obliged.
Upvotes: 0
Reputation: 4428
Try this:
import { Foo } from './foo';
jest
.spyOn(Foo, 'doSomething')
.mockImplementation(() => console.log('mock implementation'));
Foo.doSomething();
Upvotes: 1