reactjs - 使用 React cookies 运行测试时无效 prop `cookies`

标签 reactjs unit-testing jestjs enzyme react-cookie

我正在使用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: '/' });
  });

测试正确运行并通过,但是在控制台中出现了传递到 props 的 proptype 不正确的警告:

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`.

如何在 stub remove 方法时将 Cookies 实例提供到我的测试中?

最佳答案

通过初始化类然后修改方法使其工作,完整代码:

  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: '/' });
  });

关于reactjs - 使用 React cookies 运行测试时无效 prop `cookies`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55896588/

相关文章:

javascript - 开 Jest - 在描述 block 中导入多个测试,重用 beforeEach() 中定义的变量

javascript - 需要帮助使用某些类型的样式和 react

reactjs - 如何检查 firebase 中的嵌套文档和集合是否存在,如果不存在,如何在 native react 中创建

unit-testing - 单元测试和 Web 应用程序 - 资源

unit-testing - Pycharm 单元测试交互式调试命令行不起作用

typescript - 如何在 vue 组合 api 组件中使用 jest 进行单元测试?

javascript - 在 jest(NodeJs) 中编写测试来验证对象属性

html - MouseLeave 事件未触发 anchor 元素

html - 删除 React 应用程序中 div 上方的空格

php - 在 Zend_Test 工具中执行 Zend Framework Controller 时设置正确的 InvokeArg