I have this module with a function in it:
const utils = {
redirectTo(url) {
if (url) {
window.location = url;
}
},
};
export default utils;
It is used somewhere in a React component like this:
import utils from '../../lib/utils';
componentWillUpdate() {
this.redirectTo('foo')
}
Now I want to check that the value that redirectTo
is called with equals foo
.
it('should redirect if no rights', () => {
const mockRedirectFn = jest.fn();
utils.redirectTo = mockRedirectFn;
mount(
<SomeComponent />,
);
expect(mockRedirectFn).toBeCalled();
expect(mockRedirectFn).toBeCalledWith('foo');
console.log(mockRedirectFn.mock);
// { calls: [], instances: [] }
});
Thats what I've got and it does not work. How do I do this?
I have this module with a function in it:
const utils = {
redirectTo(url) {
if (url) {
window.location = url;
}
},
};
export default utils;
It is used somewhere in a React component like this:
import utils from '../../lib/utils';
componentWillUpdate() {
this.redirectTo('foo')
}
Now I want to check that the value that redirectTo
is called with equals foo
.
it('should redirect if no rights', () => {
const mockRedirectFn = jest.fn();
utils.redirectTo = mockRedirectFn;
mount(
<SomeComponent />,
);
expect(mockRedirectFn).toBeCalled();
expect(mockRedirectFn).toBeCalledWith('foo');
console.log(mockRedirectFn.mock);
// { calls: [], instances: [] }
});
Thats what I've got and it does not work. How do I do this?
Share Improve this question edited May 11, 2018 at 7:17 Joshua 3,1663 gold badges26 silver badges40 bronze badges asked Mar 29, 2017 at 1:04 SM79SM79 1,2642 gold badges15 silver badges34 bronze badges 2- where on the component is the function called? – Rei Dien Commented Mar 29, 2017 at 1:19
- componentWillUpdate, will update the desription too – SM79 Commented Mar 29, 2017 at 9:51
2 Answers
Reset to default 13You have to mock the lib/utils
module like this:
import utils from '../../lib/utils';
jest.mock('../../lib/utils', () => ({
redirect: jest.fn()
}))
it('should redirect if no rights', () => {
mount(
<SomeComponent />,
);
expect(utils.redirect).toHaveBeenCalledWith();
});
This will replace the module with a mock that just returns {redirect:jest.fn()}
. This module is also imported into you test where you then can access the spy for redirect
and test on this that it was called with the correct parameter.
This is what I ended up using:
it('should redirect if no rights', () => {
// this way we mock only one method: redirectTo
jest.mock('lib/utils', () => {
const original = require.requireActual('lib/utils');
original.default.redirectTo = jest.fn();
return original;
});
const redirectTo = require.requireMock('lib/utils').default.redirectTo;
mount(
<SomeComponent />,
);
expect(redirectTo).toHaveBeenCalled();
});