我在我的应用中使用react-cookies软件包,并试图将测试写入我的应用中。我正在尝试模拟cookie.remove
方法并对其进行验证,下面是代码:
// App.js
export class App extends Component {
static propTypes = {
cookies: PropTypes.instanceOf(Cookies).isRequired,
}
handleClick() {
// Remove data from browser cookies
this.props.cookies.remove('data', { path: '/' });
}
//测试文件
it('should be able to remove cookies', () => {
const mockFn = jest.fn();
const cookies = { remove: mockFn };
const button = mount(<App cookies={cookies} />).find('button');
button.props().onClick();
expect(mockRemove).toHaveBeenCalledTimes(1);
expect(mockRemove).toHaveBeenCalledWith('data', { path: '/' });
});
测试正常运行并通过,但是在控制台中,此警告是错误的道具类型传递给了道具:
console.error node_modules/react/node_modules/prop-types/checkPropTypes.js:20
Warning: Failed prop type: Invalid prop `cookies` of type `Object` supplied to `App`, expected instance of `Cookies`.
在存根Cookies
方法的同时如何将remove
的实例提供给测试?
答案 0 :(得分:0)
通过初始化类然后修改方法(完整代码)使其工作:
it('should be able to remove cookies', () => {
const mockFn = jest.fn();
const cookies = new Cookies();
cookies.remove = mockFn;
const button = mount(<App cookies={cookies} />).find('button');
button.props().onClick();
expect(mockRemove).toHaveBeenCalledTimes(1);
expect(mockRemove).toHaveBeenCalledWith('data', { path: '/' });
});