2

I'm writing tests with jest and enzyme for a React component which looks like this:

function Message(props) {
  return (
    <div>
      <span>{props.message}</span>
    </div>
  );
}
Message.propTypes = { message: PropTypes.string.isRequired };

I'd like to write a test that says "props.message is rendered exactly once by this component", and I'd like to do it without calling wrapper.find('span') (it's an acceptance test, not a unit test, so the fact that the message is wrapped in a <span> is an implementation detail and therefore immaterial).

I'm currently using .findWhere to return a NodeList, and then expect the length of the list to be 1:

it(`renders props.message`, function() {
    const msg = 'hello';
    const wrapper = shallow(
      <Message message={msg} />
    );
  });

  function nodeTextEqualsMessage(node) {
    // return nodes with no element name ( = text nodes)
    // and where node text = message
    return !node.name() && node.text() === msg;
  }

  const nodeList = wrapper.findWhere(nodeTextEqualsMessage);

  expect(nodeList.exists()).toBe(true);
  expect(nodeList.length).toBe(1);
});

the test passes, which is great. But if I "accidentally" update my component:

function Message(props) {
  return (
    <div>
      <span>{props.message}</span>
      <span>{props.message}</span>
    </div>
  );
}

the same test still passes, which is not so great. The snapshot of nodeList looks like this:

exports[`the component renders props.message 1`] = `"hello"`;

why is enzyme collapsing multiple findWhere results into a single node? Can I stop it from doing that? Is there an alternative enzyme method I should use instead?

thanks!

Dan O
  • 6,022
  • 2
  • 32
  • 50

0 Answers0