Reputation: 336
I have a mock file called StateService
located in a __mocks__
folder
export default {
goTo: jest.fn(),
goToNewTab: jest.fn(),
goToPreviousAppState: jest.fn(),
reload: jest.fn()
}
In my test, I want to spy goToNewTab
and check that the function has been called.
What I'm doing right now is importing the mock file into my test and then, in my test itself, I'm calling expect like this:
expect(StateService.goToNewTab).toHaveBeenCalled();
But the expect is not returning a positive value.
Upvotes: 0
Views: 700
Reputation: 6325
Let's say you have a file in services/StateService.js
(for simplicity I will only define the goToNewTab
service):
function goToNewTab() {
// Your logic here.
}
export default {
goToNewTab
};
Then, you create a mock of this module in services/__mocks__/StateService.js
:
export default {
goToNewTab: jest.fn()
};
Now, you are testing a module that calls the goToNewTab
service. Let's suppose it is placed in utils/navigation.js
:
import StateService from '../services/StateService';
export default function() {
StateService.goToNewTab();
}
The test for such a module making use of the mocked service would look like:
import StateService from '../services/StateService';
import navigation from './navigation';
jest.mock('../services/StateService');
it('Should mock call', () => {
navigation();
expect(StateService.goToNewTab).toHaveBeenCalled();
});
Note that if you are requiring the StateService
module in your test, you need to explicitly call jest.mock
of the module, as stated in the documentation.
Upvotes: 1