简体   繁体   中英

How to test if element(tag) rendered with jest/enzyme?

I cannot understand how properly test in element is rendered or not. I wrote such a test:

const props = {
  type: 'test_plan',
  renewal: '25.06.2019',
  subscriptionName: 'Test',
};
test('test component elements render', () => {

     const wrapper = mount(<Component {...props} />);
     console.log(wrapper.debug())
     expect(wrapper.find('.link')).to.have.lengthOf(0);
     expect(wrapper.find('type')).to.have.lengthOf(1);

    });

This what I have in the console when debug component:

<div className="wrapper">
        <div className="mobile">
          <h3>
            Test
          </h3>
        </div>
        <div className="inner">
          <h3>
            Test
          </h3>
          <div className="type">
            <h4>
              Test Type 1
            </h4>
            <span>

              25.06.2019
            </span>
          </div>
        </div>
      </div>

and this is error that I have Cannot read property 'have' of undefined

How properly test if element in component rendered or no???

.to.have.lengthOf is an assertion from Chai .

So you can either require expect from Chai and use the Chai assertion:

import * as React from 'react';
import { mount } from 'enzyme';

const expect = require('chai').expect;  // <= use expect from Chai

const Component = () => (<div><div className="type"></div></div>);

test('test component elements render', () => {
  const wrapper = mount(<Component />);
  expect(wrapper.find('.link')).to.have.lengthOf(0);  // Success!
  expect(wrapper.find('.type')).to.have.lengthOf(1);  // Success!
});

...or you can use the .toHaveLength assertion included in Jest :

import * as React from 'react';
import { mount } from 'enzyme';

const Component = () => (<div><div className="type"></div></div>);

test('test component elements render', () => {
  const wrapper = mount(<Component />);
  expect(wrapper.find('.link')).toHaveLength(0);  // Success!
  expect(wrapper.find('.type')).toHaveLength(1);  // Success!
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM