I am trying to understand how to mock a function
call inside a module when function returns an object, say I have a file
Sample.ts
export function food(){
return new Fruit();
}
export function taste(){
return food().getTaste();
}
Now let's say I am trying to test a scenario wether taste()
throws an error when getTaste()
throws an error.
I understand I can take advantage of "ES6 module cyclic dependency" to import the module into itself as:
import * as sample from './sample';
export function food(){
return new Fruit();
}
export function taste(){
return sample.food().getTaste();
}
But I am not sure while testing how do I return mocked Fruit mockedReturnValue
does not allow a "Argument of type 'typeof jest'"
const mockedFruit = jest.mock("./fruit", () => ({
getTaste: jest.fn().mockImplementation(() => {
throw new Error("Test Error");
}),
promise: jest.fn()
}));
test('taste', () => {
const sample = require('./sample');
jest.spyOn(sample, 'food').mockReturnValue(mockedFruit);
expect(sample.taste()).toThrowError();
})