【问题标题】:How to test if a React component contains another component with Tape and Enzyme?如何测试一个 React 组件是否包含另一个带有 Tape 和 Enzyme 的组件?
【发布时间】:2016-05-20 04:40:24
【问题描述】:

假设我有以下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()
})

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

【问题讨论】:

    标签: unit-testing testing reactjs enzyme


    【解决方案1】:

    我明白了。它是:

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

    来自enzymeshallow 函数返回一个包装器,该包装器具有find 方法。 find 返回一个具有属性length 的对象。如果我的组件中有两个AppBars,length 将等于2,所以我可以测试它以查找=== 1 以完成我的测试。

    【讨论】:

    • 使用 Enzyme,您还应该能够使用它的匹配器来编写它。所以:assert.equal(wrapper.find('AppBar').length === 1, true) 可能变成:expect(wrapper.find('AppBar')).toHaveLength(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。

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

    【讨论】:

      猜你喜欢
      • 2014-12-06
      • 2023-02-09
      • 2018-03-12
      • 2017-03-25
      • 2019-03-10
      • 2021-06-23
      • 2017-05-03
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多