Reputation: 10062
I have a function that I am importing from another file:
import { getMenu } from '../utils/request';
Then I have a method that calls this function that I want to test (I want to test that the method really calls this function):
it('handleDateChange should call getMenu when NOT passed state date', ()=> {
const dashboard = shallow(<Dashboard/>);
const today = new Date();
var spy = sinon.spy(getMenu);
dashboard.setState({ selectedDate: 'blah' });
dashboard.instance().handleDateChange(today);
expect(spy.called).toBe(true);
});
The funny thing is, I get some console output from the getMenu method, so I know the method has been called.
But spy.called still return false.
What am I doing wrong?
Upvotes: 0
Views: 715
Reputation: 111042
The problem is that you cant mock stuff in modules with sinon that this has any effect on other places were this module is imported. So you only spy on the function that is imported in your test. The solution when using jest would be to mock the module and import it in your test.
import { getMenu } from '../utils/request';
jest.mock('../utils/request', () => ({getMenu: jest.fn()}))
it('handleDateChange should call getMenu when NOT passed state date', ()=> {
const dashboard = shallow(<Dashboard/>);
const today = new Date();
dashboard.setState({ selectedDate: 'blah' });
dashboard.instance().handleDateChange(today);
expect(getMenu).toHaveBeenCalled();
});
So first we import the module, then we mock it so that getMenu
is a jest spy. Note that when the tests run all jest.mock
calls get called before all the import stuff is happened, so in your test and in the module you want to test, the request
module is just and object with getMenu
which is the spy. By importing the module in you test as well you are able to test that it was called.
Upvotes: 1