Mathías Padula
Mathías Padula

Reputation: 75

About state in react js enzyme

I am trying to build a test for my Class component. I want to test the state of my component and compare the state values with de rendered result. I have a basic component that only shows a doots tooltip and shows options depending on the state value. It is a simple component like this:

import React, { Component } from 'react';
import './DotsTooltip.css';
import { translate } from 'react-i18next';

class DotsTooltipPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      optionsVisible: false,
      label: '',
    };
  }

  componentDidMount() {
//code here
  }


  render() {
    const { optionsVisible, label } = this.state;
    const { icon } = this.props;
    return (
      <div className="dots-tooltip-container">
My component content
      </div>
    );
  }
}

const DotsTooltip = translate('translations')(DotsTooltipPage);

export { DotsTooltip };

so then I have a test like this:

import { DotsTooltip } from './DotsTooltip';
import React from 'react';
import { shallow } from 'enzyme';

const setup = (props = {}, state = null) => {
  const wrapper = shallow(<DotsTooltip {...props} />);
  if (state) wrapper.setState(state);
  return wrapper;
};

describe('DotsToolTip', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = setup({ icon: null });
  });

  it('render', () => {
    expect(wrapper);
  });

  it('initial state should', () => {
    expect(wrapper.state().optionsVisible).toEqual(false);
  });
});

The test fails and shows me this error: Cannot read property 'optionsVisible' of null

I have read carefully the enzyme documentation but I don't know why it happens.

Upvotes: 0

Views: 46

Answers (1)

Isa Gul
Isa Gul

Reputation: 56

You should use only state instead of state() and get an instance of the component.

import {shallow} from 'enzyme';

const component = shallow(<DotsTooltip />);
const instance = component.instance();
expect(instance.state.optionsVisible).toBe(false);

Upvotes: 1

Related Questions