Jest tests failing only with coverage

Viewed 1761

I have the issue that if I run my test without the --coverage option everything passes, but as soon as I run jest with the --coverage option some of my test fail.

Here is the log:

Button › Primary button › should render a primary button

  undefined:3:457: property missing ':'

  at Object.it (src/components/Buttons/Button/Button.test.js:13:24)
  at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)

And the test:

it('should render a primary button', () => {
  const props = { primary: true };

  const rendered = renderer.create(<Button { ...props }>Some Button</Button>).toJSON();
  expect(rendered).toMatchSnapshot();
});

The failing line is expect(rendered).toMatchSnapshot();

Anyone any ideas?

1 Answers

I fixed this issue. But I think it was a quite specific one.

We are using styled components and I did something like this:

const BaseButton = styled.button`
  ${ noTouchDevice && `
    :hover {
      cursor: ${ ({ disabled }) => (disabled ? 'not-allowed' : 'initial') };
    }
  ` }
`;

Which is not working since the nested template literal is not handled by styled-component like the outer one. Which means if styled-components finds a function in the outer string literal it invokes it and passes the component props as parameters. But a nested template literal will not be handled like this.

This is why in the snapshots I got something like this:

.c0:hover {
  cursor: ({ disabled }) => disabled ? 'not-allowed' :'initial';
}

instead of

.c0:hover {
  cursor: not-allowed;
}

Just running the tests worked fine, but with coverage collection it failed there comparing the snapshots.

So I simply changed my code to just using the ternary operator like

const BaseButton = styled.button`
  ${ noTouchDevice && `
    :hover {
      cursor: ${ disabled ? 'not-allowed' : 'initial' };
    }
  ` }
`;

and it worked fine.

What I still do not know, is why the error only occurred when collection the coverage. To be honest I did not wanted to invest more time yet but I assume it has to do with how the test are invoked when jest/istanbul is collection the coverage.

Related