我需要测试此功能:
import dependency from 'dependency';
export default values => (dispatch) => {
dispatch(dependency(values));
// More code
};
我进行了一项测试,该测试断言dispatch
被称为dependency
:
import functionToTest from 'function-to-test';
jest.mock('dependency', () => () => 'dependency res');
describe('functionToTest', () => {
const dispatch = jest.fn();
functionToTest({ foo: 'bar' })(dispatch);
test('test', () => {
expect(dispatch.mock.calls[0][0]).toBe('dependency res');
});
});
我需要断言dependancy
是用{ foo: 'bar' }
调用的。我尝试命名依赖项模拟,但是当我console.log
时它是未定义的:
import functionToTest from 'function-to-test';
const dependencyMock = jest.mock('dependency', () => () => 'dependency res');
describe('functionToTest', () => {
const dispatch = jest.fn();
functionToTest({ foo: 'bar' })(dispatch);
test('test', () => {
expect(dispatch.mock.calls[0][0]).toBe('dependency res');
console.log(dependencyMock.mock.calls) // undefined
});
});
我试图创建一个新的玩笑功能spy
,希望我可以检查它的参数,但这返回了错误
import functionToTest from 'function-to-test';
const spy = jest.fn(() => 'save-form-data');
const dependencyMock = jest.mock('dependency', () => spy);
describe('functionToTest', () => {
const dispatch = jest.fn();
functionToTest({ foo: 'bar' })(dispatch);
test('test', () => {
expect(dispatch.mock.calls[0][0]).toBe('dependency res');
console.log(dependencyMock.mock.calls) // undefined
});
});
jest.mock()
的模块工厂不允许引用任何 范围外的变量。
答案 0 :(得分:0)
您已经关闭!
您需要在传递给jest.mock
的模块工厂函数中移动模拟函数。
然后,您只需要将dependency
导入测试并检查它是否按预期被调用:
import functionToTest from 'function-to-test';
import dependency from 'dependency'; // <= dependency will be...
jest.mock('dependency', () =>
jest.fn(() => 'dependency res') // <= ...this mock function
);
describe('functionToTest', () => {
it('should dispatch dependency', () => {
const dispatch = jest.fn();
functionToTest({ foo: 'bar' })(dispatch);
expect(dispatch.mock.calls[0][0]).toBe('dependency res'); // Success!
expect(dependency).toHaveBeenCalledWith({ foo: 'bar' }); // Success!
});
});
请注意,默认情况下,babel-jest
个提升jest.mock
调用会在测试文件中的其他任何内容之前运行,因此传递给jest.mock
的模块工厂函数必须完全独立。 / p>