Nano
Nano

Reputation: 847

Render child components with Enzymejs tests

I'm trying to test a simple component that take some props (it have no state, or redux connection) with Enzyme, it works for the plain elements like <div /> and so on, but when i try to test if the element rendered by the child component exists, it fails.

I'm trying to use mount but it spit me a lot of errors, i'm new in this so, here is my code:

import React, { Component } from 'react';
import WordCloud from 'react-d3-cloud';

class PredictWordCloud extends Component {
  render() {
    const fontSizeMapper = word => Math.log2(word.value) * 3.3;
    const { size, data, show } = this.props;

    if (!show)
      return <h3 className='text-muted text-center'>No data</h3>

    return (
      <section id='predict-word-cloud'>
        <div className='text-center'>
          <WordCloud
            data={data}
            fontSizeMapper={fontSizeMapper}
            width={size}
            height={300} />
        </div>
      </section>
    )
  }
}

export default PredictWordCloud;

It's just a wrapper for <WordCloud />, and it just recieves 3 props directly from his parent: <PredictWordCloud data={wordcloud} size={cloudSize} show={wordcloud ? true : false} />, anything else.

The tests is very very simple for now:

import React from 'react';
import { shallow } from 'enzyme';
import PredictWordCloud from '../../components/PredictWordCloud.component';
import cloudData from '../../helpers/cloudData.json';

describe('<PredictWordCloud />', () => {
  let wrapper;

  beforeEach(() => {
     wrapper = shallow(<PredictWordCloud data={cloudData} size={600} show={true} />)
  });

  it('Render without problems', () => {
     const selector = wrapper.find('#predict-word-cloud');
     expect(selector.exists()).toBeTruthy();
  });
});

For now it pass but if we change the selector to: const selector = wrapper.find('#predict-word-cloud svg'); where the svg tag is the return of <Wordcloud /> component, the tests fails because the assertion returns false.

I tried to use mount instead of shallow, exactly the same test, but i get a big error fomr react-d3-cloud:

PredictWordCloud Render without problems TypeError: Cannot read property 'getImageData' of null.

This is specially weird because it just happens in the test environment, the UI and all behaviors works perfectly in the browser.

Upvotes: 1

Views: 3009

Answers (1)

WitVault
WitVault

Reputation: 24130

You can find your component directly by Component name. Then you can use find inside your sub-component as well.

e.g

  it('Render without problems', () => {
     const selector = wrapper.find('WordCloud').first();
     expect(selector.find('svg')).to.have.length(1);

  });

or You can compare generated html structure as well via

  it('Render without problems', () => {
     const selector = wrapper.find('WordCloud').first();
     expect(selector.html()).to.equal('<svg> Just an example </svg>');

  });

Upvotes: 1

Related Questions