ReactJS&酶:将元素内容与字符串匹配

时间:2016-08-04 09:40:53

标签: javascript testing reactjs mocha enzyme

我在React.js中有简单的Intro组件,它呈现h1和p。

我正在尝试为传递的h1& amp;用酶进行p串,但我无法做到这一点。这段代码有什么问题?

it('description of element is okay <p>', () => {
  const wrapper = shallow(<Intro title="Heading of element" description="Description of element" />);
  expect(wrapper.find('p').text().to.contain("Description of element")); // This is not working!
});

如果我控制台登录wrapper.find('p').text()它没有未定义......然而控制台说的是这样的:

  1) (Component) Intro contains a single <p>:
 TypeError: Cannot read property 'contain' of undefined
  at Context.<anonymous> (test/components/alerts/alert.spec.js:19:12)

3 个答案:

答案 0 :(得分:3)

最有可能断言应该是这样的:

expect(wrapper.find('p').text()).to.contain('Description of element')

expect的作用类似于:

expect(something).to.do.something

答案 1 :(得分:1)

您在酶包装器上调用.to.contain,而不是在期望对象上。所以不要这样:

expect(wrapper.find('p').text().to.contain("Description of element"));

你应该:

expect(wrapper.find('p').text()).to.contain("Description of element");

答案 2 :(得分:0)

用于检查字符串内容的新API

expect(wrapper.find('p').text()).toContain('text to check')

作为参考,请检查jest toContain documentation