[英]How to mock external module method?
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:它在 React 组件中的某个地方使用,如下所示:
import utils from '../../lib/utils';
componentWillUpdate() {
this.redirectTo('foo')
}
Now I want to check that the value that redirectTo
is called with equals foo
.现在我想检查redirectTo
被调用的值是否等于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?我该怎么做呢?
You have to mock the lib/utils
module like this:你必须像这样模拟lib/utils
模块:
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()}
.这将用只返回{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.这个模块也被导入到你的测试中,然后你可以访问间谍进行redirect
并测试它是否使用正确的参数调用。
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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.