I have a reducer that say does something like this:
return {
...state,
result: myResult(valA, valB)
}
and the myResult
function is defined in the same file above the reducer
currently I'm getting a failing test because the values that I pass in to myResult
are undefined
how can I mock this function out using jest?
I know I can do this:
const myMock = jest.fn()
myMock.mockReturnValueOnce(10)
but how do I specifically tell the test file which actual function it should mock in the main file?
I feel like I want to do something like
import { myResult } from './index'
myResult = jest.fn()
myResult.mockReturnValueOnce(someObject)
but im not sure that would work because the way to test reducers is to have an initial object, an expected object result and then pass through an action. whereas the function I want to test belongs inside the result object key in the reducer
does that make sense?
What I usually do is the following:
First, I mock my object prior to requiring the class I'm testing:
jest.doMock('dependancy', () => {
return {
doSomething: () => {
return {
set: jest.fn(),
get: jest.fn()
};
}
};
});
Then upon execution I extract the parameter passed to the mock eg
myObject.myFunction(extension);
expect(dependancy.get).toHaveBeenCalled();
const callback = dependancy.get.mock.calls[0][1];
Then simply execute the callback myself and extract any other parameters or pass in any additional mocks to the callback parameters.
callback(undefined, undefined);
Hope this helps.
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.