Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a React component contains another component with Tape and Enzyme?

Suppose I have the following React component:

import React from 'react'
import AppBar from 'material-ui/lib/app-bar'

class NavBar extends React.Component {
  render () {
    return (
      <div>
        <AppBar
          title='My NavBar Title'
        />
      </div>
    )
  }
}

export default NavBar

And I want to set up a test to make sure the user sees a material-ui AppBar when the NavBar is rendered, using Tape and Enzyme for that:

import NavBar from './NavBar'
import React from 'react'
import test from 'tape'
// import { I don't know exactly what to import here. Maybe `shallow`? } from 'enzyme'

test('NavBar component test', (assert) => {
  test('I should see an AppBar', (assert) => {
    // How can I test for it?
    // Also, can I test only for the presence of `AppBar`, without
    // necessarily for the overriding of props? For example,
    // even if I actually have <AppBar title='My NavBar title' />,
    // can I test only for `AppBar`?
    assert.end()
  })
  assert.end()
})

How can I do it properly?

like image 401
Marcus Vinícius Monteiro Avatar asked Nov 29 '22 23:11

Marcus Vinícius Monteiro


1 Answers

I got it. It is:

test('I should see one AppBar', (assert) => {
  const wrapper = shallow(<NavBar />)
  assert.equal(wrapper.find('AppBar').length === 1, true)
  assert.end()
})

The shallow function from enzyme returns a wrapper which has the method find. find returns an object that has the property length. If I had two AppBars in my component, length would be equal to 2, so I can test it for === 1 to complete my test.

like image 95
Marcus Vinícius Monteiro Avatar answered Dec 05 '22 04:12

Marcus Vinícius Monteiro