6

在测试使用 className 使用酶(安装或浅)设置 css 类的反应组件时,我能够在它是 div 时正确测试,但无法让它在 h1 标签上工作。

这是一些

  • 与安装或浅的事情有关?
  • 这是我想念的东西吗?
  • 它是一个错误吗?

任何想法表示赞赏!

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')
});


});

试验结果:

请注意调试日志,其中显示了带有 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
4

2 回答 2

5

诡异的。它应该工作。

无论如何,您可以尝试利用 Enzyme 的 API。

对于这个特定的测试,.hasClass()应该完成这项工作并且更清楚它的意图:

expect(wrapper.find('h1').hasClass('myheader')).to.eq(true)
于 2017-01-19T13:41:17.600 回答
2

这里的问题是您的导入import styles from './styles.module.css'实际上没有被加载。

您可能在测试设置文件中有一些东西可以模拟出任何带有 css 扩展名的东西:

require.extensions['.css'] = function () {
  return null;
};

我没有足够的代表,否则我会对此发表评论。不幸的是,我还不知道实际导入这些样式的方法,你可以从我的问题中看出:WebPack LESS imports when testing with Mocha

于 2016-07-20T18:10:00.673 回答