运行带有react cookie的测试时,无效的prop`cookies

问题描述 投票:1回答:1

我在我的应用中使用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`.

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

reactjs unit-testing jestjs enzyme react-cookie
1个回答
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: '/' });
  });
© www.soinside.com 2019 - 2024. All rights reserved.