Reputation: 20222
I have the following test:
const mockedObject = {
mockedMethod: jest.fn((someKey, someValue) => {
return {someKey: 'someValue'}
})
};
jest.doMock('../myObject', () => {
return mockedObject;
});
testedObject.testedMethod();
expect(mockedObject.mockedMethod).toHaveBeenCalled();
Here, in the testedObject
, I am importing myObject
. I would like to mock that import and pass mockedObject instead
.
After looking at this question and this question, I think the above code should be good, however mockedObject.mockedMethod
is never called even though testedObject
is making the call.
So what is wrong with the mocking done in this test?
Upvotes: 0
Views: 2024
Reputation: 9978
I can think of some choices.
One thing that could be happening is that you are mocking the import after your tested object has required it and you cannot modify that. If that is your case, then make sure you make the instance of the object only after you have modified the package.
Another option is to create a folder mocks and create a file .js called exactly like your module or import and then return whatever you need. This works best for global dependencies.
Lastly, what you also can do is to make your tested object receive the dependency as a parameter, so you can override the import inside the file.
Hope it helps
Upvotes: 0
Reputation: 160
You call
testedObject.testedMethod()
but expect
mockedObject.mockedMethod)
try this code:
const mockedObject = {
testedMethod: jest.fn((someKey, someValue) => {
return {someKey: 'someValue'}
})
};
jest.doMock('../myObject', () => {
return mockedObject;
});
testedObject.testedMethod();
expect(mockedObject.testedMethod).toHaveBeenCalled();
Upvotes: 1