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

时间:2016-02-10 00:33:12

标签: unit-testing 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

我想设置一个测试,以确保用户在呈现NavBar时看到material-ui AppBar,并使用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()
})

我该怎么做呢?

2 个答案:

答案 0 :(得分:11)

我明白了。它是:

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

来自enzyme的{​​{3}}函数返回一个包含方法shallow的包装器。 find返回具有属性length的对象。如果我的组件中有两个AppBarlength将等于2,那么我可以测试它=== 1来完成我的测试。

答案 1 :(得分:2)

我没有使用胶带和酶,但根据我的理解,问题与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);
});

确保AppBar确实是您要搜索的组件的displayName。

您将获得与谓词匹配的组件数组,因此您可以检查长度是否为&gt; 0

相关问题