【问题标题】:Invalid prop `cookies` when running test with react cookies使用反应 cookie 运行测试时,道具“cookies”无效
【发布时间】:2019-09-17 16:16:47
【问题描述】:

我在我的应用程序中使用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: '/' });
  });

测试正常运行并通过,但是在控制台中会出现以下警告,提示 proptype 传递到 props 中:

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

如何在存根remove 方法的同时将Cookies 的实例提供给我的测试?

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme react-cookie


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 1970-01-01
      • 2017-11-29
      • 2021-04-07
      • 2021-06-30
      • 2021-03-15
      • 1970-01-01
      • 2012-06-30
      • 2023-03-24
      相关资源
      最近更新 更多