1

I'm using react-cookies package in my app and trying to write tests into my app. I'm trying to mock cookie.remove method and validate it, below are the codes:

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

// Test file

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

The test ran properly and passed, however in the console there is this warning of incorrect proptype passed into the 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`.

How can I supply the instance of Cookies into my test while stubbing the remove method?

Jee Mok
  • 6,157
  • 8
  • 47
  • 80

1 Answers1

1

Got it working by initializing the class then modify the method, full code:

  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: '/' });
  });
Jee Mok
  • 6,157
  • 8
  • 47
  • 80