Search code examples
jestjsenzymetest-coverage

Jest and enzyme - how to test function that is property to child component (for test coverage)


To simplify - I have a component, let say <Label /> and I'm using it like this:

...
<Label
  labelText="Some text"
  renderText={(text) => {
    const cssClass = text.length < 5 ? 'one-class' : 'other-class';
    return <b className={cssClass}>{text}</b>;
  }}
/>
...

So - I have a property which is a function that defines how the text will be displayed. All is fine and it's working.

When I run jest --coverage however - it shows me that the line with setting cssClass is uncovered.

How can I test that line?


Solution

  • There are 2 ways testing that. And you need 2 test-cases: one for text.length< 5 and another one for text.length>= 5

    First aprroach is using mount(). Here you need to figure out where text argument is coming from(passing as a props to your component or what's the way). Then you will get <Label> rendered in some <span> or whatever. And you will need to check if there is inside <b class='one-class'>text</b> or <b class='other-class'>text1</b>

    Another approach is using shallow() on your component. Then you will be able to test renderText explicitly:

    it('renders label with text having length of 4', () => {
      const renderText = shallow(<YourComponent ... >).find(Label).props().renderText;
      expect(renderText('1234')).toEqual(<b className="one-class">1234</b>);
    });
    
    it('renders label with text having length of 5 or more', () => {
      const renderText = shallow(<YourComponent ... >).find(Label).props().renderText;
      expect(renderText('12345')).toEqual(<b className="other-class">12345</b>);
    });