I am having an issue with mocking functions called from within my module. when the mocked function is called from the test, it works as expected. but when that same mocked function is called from the library, it calls the actual function.
I have tried the jest.mock('./myModule', () => {})
approach, and enableAutomock
as well, but with the same results.
I feel like i have not had this problem in other projects, but have looked through my jest configuration, and don't see anything that would effect it.
what am i missing here? how can i mock functions called internally within my module?
// myModule.js
export function foo() {
return 'foo'
}
export function bar() {
return foo()
}
// myModule.test.js
import * as myModule from './myModule';
jest.spyOn(myModule, 'foo').mockReturnValue('mock foo');
// i have also tried...
// jest.mock('./myModule', () => {
// ...(jest.requireActual('./myModule')),
// foo: jest.fn().mockReturnValue('mock foo')
// });
it('should', () => {
expect(myModule.foo()).toEqual('mock foo'); // PASS: returns 'mock foo'
expect(myModule.bar()).toEqual('mock foo'); // FAIL: returns 'foo'
});
I found using ts-jest
in my jest config, allowed these tests to run as i expected
transform: {
'^.+\\.[tj]sx?$': ['ts-jest'],
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.