如何测试React组件是否包含带有Tape和Enzyme的另一个组件?

Mar*_*iro 3 testing unit-testing reactjs enzyme

假设我有以下React组件:

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
Run Code Online (Sandbox Code Playgroud)

我想设置一个测试,以确保用户在渲染时看到一个材料-ui AppBarNavBar,使用TapeEnzyme:

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()
})
Run Code Online (Sandbox Code Playgroud)

我怎么能正确地做到这一点?

Mar*_*iro 12

我知道了.它是:

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

shallow从功能enzyme返回其具有方法的包装find.find返回具有该属性的对象length.如果AppBar我的组件中有两个s,length则等于2,所以我可以测试它=== 1以完成我的测试.

  • 使用Enzyme,您还应该能够使用其匹配器来编写它.所以:`assert.equal(wrapper.find('AppBar').length === 1,true)`可能成为:`expect(wrapper.find('AppBar')).toHaveLength(1)` (4认同)

gor*_*181 4

我没有使用胶带和酶,但根据我的理解,这个问题与React测试工具更相关。

无论如何,工具都有方法:https://facebook.github.io/react/docs/test-utils.html#findallinrenderedtree

您可以使用它来查看组件是否像这样渲染:

const u = require('react-addons-test-utils');
const hasAppBar = u.findAllInRenderedTree(NavBar, (component) => {
   return u.isCompositeComponentWithType(component, AppBar);
});
Run Code Online (Sandbox Code Playgroud)

只需确保 AppBar 确实是您正在搜索的组件的显示名称。

您将返回与谓词匹配的组件数组,因此您可以检查长度是否> 0。