我无法增加此行handleSave
的覆盖范围,我将其作为prop
传递给我的组件。但是,我正在测试用例中从容器文件中导入mapStateToProps
,并使用.toBeTruthy()
来验证测试用例。
这是我的代码要点
export const mapStateToProps = (state, ownProps) => {
return {
handleSave: title => ownProps.history.push(setTitle(title)),
};
};
这是我编写的测试用例
it('mapStateToProps test case', () => {
const result = mapStateToProps(state, ownProps);
expect(result.handleSave).toBeTruthy();
});
有人可以帮忙吗?我应该怎么做才能覆盖handleSave
?
您可以做的是模拟ownProps
并测试模拟功能,例如:
const mockFn = jest.fn();
const ownProps = {
history: {
push: mockFn
}
}
const result = mapStateToProps(state, ownProps);
// Now call the handle save function
result.handleSave("My title");
// And then as follows:
// This will ensure that your function is calling ownProps history push method.
expect(mockFn).toBeCalled();
// To check the funciton has only been called once
expect(mockFn.mock.calls.length).toBe(1);
// This is to check if the correct argument has been passed. Be sure to pass in what your `setTitle` funciton returns
expect(mockFn.mock.calls[0][0]).toBe("My title");