mercredi 22 mars 2017

Jest test for setTimeout within componentDidUpdate

I have a component that uses componentDidUpdate to dispatch an action 5 seconds after the component receives props:

componentDidUpdate() {
  if (this.props.app.temporaryMessages.length > 0) {
    setTimeout(() => {
      this.props.clear();
    }, 5000);
  }
}

This works well, but when testing I'm not able to check that props.clear has run after the timeout:

describe('<GlobalMessages />', () => {
  jest.useFakeTimers();
  let props;
  beforeEach(() => {
    props = {
      app: {
        temporaryMessages: [],
        permanentMessages: [],
      },
      clear: jest.fn(),
    };
  });

  it('Renders initially', () => {
    render(<GlobalMessages {...props} />);
    expect(props.clear).not.toHaveBeenCalled();
    props.app.temporaryMessages = [
      { msg: 'msg 2' },
      { msg: 'msg 1' },
    ];
    render(<GlobalMessages {...props} />);
    jest.runAllTimers();
    expect(props.clear).toHaveBeenCalled();
  });
});

I have a similar working which doesn't use setTimeout, so I believe I have this setup right.

Aucun commentaire:

Enregistrer un commentaire