最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJS & Enzyme: Matching elements contents to string - Stack Overflow

programmeradmin3浏览0评论

I have simple Intro ponent in React.js which renders a h1 and a p.

I am trying to write a test for the passed h1 & p strings with Enzyme but I'm unable to do this. What is wrong with this code?

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

If I console log the wrapper.find('p').text() it's not undefined... And yet the console says like this:

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

I have simple Intro ponent in React.js which renders a h1 and a p.

I am trying to write a test for the passed h1 & p strings with Enzyme but I'm unable to do this. What is wrong with this code?

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

If I console log the wrapper.find('p').text() it's not undefined... And yet the console says like this:

  1) (Component) Intro contains a single <p>:
 TypeError: Cannot read property 'contain' of undefined
  at Context.<anonymous> (test/ponents/alerts/alert.spec.js:19:12)
Share Improve this question edited Aug 4, 2016 at 9:44 HiDeoo 10.6k8 gold badges51 silver badges50 bronze badges asked Aug 4, 2016 at 9:40 CapuchinCapuchin 3,7956 gold badges31 silver badges41 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Most probably assertion should look like:

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

expect works like:

expect(something).to.do.something

New API to check string content is

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

For reference please check jest toContain documentation

You are calling .to.contain on the enzyme wrapper, not on the expect object. So instead of this:

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

You should have:

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

评论列表(0)

  1. 暂无评论