2
votes

I am looking for a solution using React, Jest and Enzyme. I am a newbie to these technologies.

I could get a few simple tests to run. Now here is what I want to test:

<div className="trow">
            <div className="tcolid" >101</div>
            <div className="tcolname">Joe</div>
            <div className="tcolgender">M</div>
          </div>

          <div className="trow">
            <div className="tcolid" >102</div>
            <div className="tcolname">Abc</div>
            <div className="tcolgender">F</div>
          </div>

          <div className="trow">
            <div className="tcolid" >103</div>
            <div className="tcolname">Xyz</div>
            <div className="tcolgender">F</div>
          </div>
          ...
          ...

My React component consumes data from a rest api. The API can return multiple records male and/or female. My requirement is to ensure only a single male employee to be rendered in UI. I have that achieved - not a problem.

When I am writing tests using Jest and Enzyme I want to check that when I render I only render a single html element having a value 'M'.

Here is what I have tried - Jest / Enzyme does not like it.

expect (wrapper.find("div.tcolgender").text()).toEqual("M").toHaveLength(1);

This does not work. I looked at the Enzyme API - dont find any 'count' or similar such method. Note - this is a 'full' render and not a 'shallow' render.

1

1 Answers

6
votes

you can write your selector to match all of the divs with M contents

const children = wrapper.find('div.tcolgender[children="M"]')

and assert the children will have length of one

expect(children).toHaveLength(1);

working example