使用Enzyme在组件无状态功能时按显示名称查找组件

时间:2016-02-14 16:00:44

标签: unit-testing testing reactjs stateless enzyme

我有以下组件:

// Hello.js
export default (React) => ({name}) => {
  return (
    <div>
      Hello {name ? name : 'Stranger'}!
    </div>
  )
}

// App.js
import createHello from './Hello'

export default (React) => () => {
  const Hello = createHello(React)
  const helloProps = {
    name: 'Jane'
  }
  return (
    <Hello { ...helloProps } />
  )
}

// index.js
import React from 'react'
import { render } from 'react-dom'
import createApp from './App'

const App = createApp(React)

render(
  <App />,
  document.getElementById('app')
)

我想设置一个测试,以查看App组件是否包含一个Hello组件。我使用TapeEnzyme尝试了以下内容:

import createApp from './App'
import React from 'react'
import test from 'tape'
import { shallow } from 'enzyme'

test('App component test', (assert) => {
  const App = createApp(React)
  const wrapper = shallow(<App />)
  assert.equal(wrapper.find('Hello').length === 1, true)
})

但结果是length结果的find属性等于0,当我期望它等于1时。那么,我如何找到我的Hello组件?

2 个答案:

答案 0 :(得分:19)

在这种情况下,你可以做几件事。 Enzyme可以基于构造函数的静态.displayName.name属性或引用相等性来匹配组件构造函数。因此,以下方法都应该有效:

直接参考

您可以导入测试中的实际组件,并使用对组件的直接引用来查找它们:

// NavBar-test.js

import NavBar from './path/to/NavBar';  
...  
wrapper.find(NavBar).length)

命名函数表达式

如果使用命名函数表达式来创建无状态功能组件,则名称仍然有效。

// NavBar.js  

module.exports = function NavBar(props) { ... }

静态.displayName属性

您可以在组件上添加静态.displayName属性:

// NavBar.js

const NavBar = (props) => { ... };
NavBar.displayName = 'NavBar';

答案 1 :(得分:0)

尝试导入文件顶部的 Hello 组件,然后更新断言以查找实际组件而不是其名称。如下图:

import createApp from './App'
import Hello from './Hello'
import React from 'react'
import test from 'tape'
import { shallow } from 'enzyme'

test('App component test', (assert) => {
  const App = createApp(React)
  const wrapper = shallow(<App />)
  assert.equal(wrapper.find(Hello).length === 1, true)
})

顺便说一句,对于所有的酶用户来说,断言应该是这样的:

expect(wrapper.find(Hello)).toHaveLength(1);