假设我有以下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,并使用Tape和Enzyme:
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()
})
我该怎么做呢?
答案 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
的对象。如果我的组件中有两个AppBar
,length
将等于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