在使用enzyme(mount或shallow)测试一个使用className设置css类的react组件时,如果它是一个div,我能够正确地进行测试,但是无法在h1标签上运行。
这是由于:
- mount或shallow的问题吗?
- 我是否遗漏了一些东西?
- 还是有bug?
欢迎任何想法!
JSX:
import React from 'react'
export const PageNotFound = ({heading, content, wrapperCSS, headingCSS, contentCSS}) => (
<div className={ wrapperCSS }>
<div className={ contentCSS }>
{ content }
</div>
<h1 className={ headingCSS }>{ heading }</h1>
</div>
)
PageNotFound.propTypes = {
heading: React.PropTypes.string,
content: React.PropTypes.string,
wrapperCSS: React.PropTypes.string,
headingCSS: React.PropTypes.string,
contentCSS: React.PropTypes.string
};
PageNotFound.defaultProps = {
heading: '404',
content: 'Page Not Found',
wrapperCSS: 'wrapper',
headingCSS: 'heading',
contentCSS: 'content'
};
export default PageNotFound
规格:
import React from 'react'
import { expect } from 'chai'
import { shallow, mount } from 'enzyme'
import PageNotFound from './PageNotFound'
describe('<PageNotFound/>', function() {
let wrapper;
beforeEach(() => {
wrapper = mount(<PageNotFound contentCSS="mycontent" headingCSS="myheader" content="Message" heading="My Title" />);
})
it('Uses heading prop', () => {
expect(wrapper.find('h1').text()).to.eq('My Title')
});
it('Uses headingCSS prop', () => {
console.log(wrapper.html());
expect(wrapper.find('h1.myheader').length).to.eq(1)
});
it('Uses content prop', () => {
expect(wrapper.find('div.mycontent').text()).to.eq('Message')
});
});
测试结果:
注意调试日志显示具有class为myheader的h1,但测试失败,因为未找到h1.myheader元素。
<PageNotFound/>
✓ Uses heading prop
LOG LOG: '<div class="_2t--u"><h1 class="myheader">My Title</h1><div class="mycontent">Message</div></div>'
✗ Uses headingCSS prop
expected 0 to equal 1
r@tests.webpack.js:11:24087
assert@tests.webpack.js:14:52974
a@tests.webpack.js:14:55858
tests.webpack.js:15:17123
tests.webpack.js:14:10442
✓ Uses content prop