ThomasThiebaud ThomasThiebaud - 1 month ago 16
React JSX Question

Why do enzyme not find 'tr' in a table?

I'm writting some test using

enzyme
but I have some weird behavior. Here is my test :

import React from 'react'
import { TypeTable } from 'routes/Type/components/TypeTable'
import { shallow } from 'enzyme'
import { Table } from 'react-toolbox'

// ...

let _props, _wrapper

beforeEach(() => {
_props = {
getTypes: sinon.spy(),
types: [
{ name: 'type 1'},
{ name: 'type 2'}
]
}
_wrapper = shallow(<TypeTable {..._props} />)
})

it('Should render a <Table>', () => {
expect(_wrapper.is(Table)).to.be.true
})

it('should render 2 rows', () => {
expect(_wrapper.find('tbody').find('tr')).to.have.length(2)
})


The first test is working. The second one is not working (the assertion is failing :
expected { Object (root, unrendered, ...) } to have a length of 2 but got 0
)

But in my second test, if I print the content of my
_wrapper
using
console.log(_wrapper.html())
I get

'<table data-react-toolbox="table">
<thead>
<tr>
<th>name</th>
</tr>
</thead>
<tbody>
<tr data-react-toolbox-table="row">
<td>type 1</td>
</tr>
<tr data-react-toolbox-table="row">
<td>type 2</td>
</tr>
</tbody>
</table>'


Which seems to be ok and which contains several
tr
.

Did I missed something ?

Answer

shallow will not "render" subcomponents. It is used to test a single component and not its children. I think that using mount instead of shallow will let you test what you want.

Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components.