How can i test the state in react functional components?

Viewed 1160

I am using jest and enzyme to test my components. If i have the following class component

import React, { Component } from "react";

export class Test extends Component {
  state = {
    isLoading: false,
  };

  onClick = () => {
    this.setState({ isLoading: true });
  };
  render() {
    return (
      <div>
        <button onClick={this.onClick}>Click button</button>
      </div>
    );
  }
}

export default Test;

then to write test for this i will use:

import {Test} from "../Test";
import { shallow } from "enzyme";
import React from "react";

it('default state value for isLoading should be false', () => {
    const wrapped = shallow(<Test/>);
    const initialIsLoading = wrapped.state('isLoading');
    expect(initialIsLoading).toBe(false);
})

it('change isLoading true on button click', () => {
    const wrapped = shallow(<Test/>);
    const initialIsLoading = wrapped.state('isLoading');
    console.log(initialIsLoading);  
    wrapped.find('button').simulate('click');
    wrapped.update();
    const newValue = wrapped.state('isLoading');
    console.log(newValue);
    expect(newValue).toEqual(true);
})

but if my component is functional then i get error - state cannot be used on functional components

when i run my tests.

How can i test my functional components state ?

1 Answers

shallow wrapper doesn't support hooks, which provide state to functional components. You can either use Enzyme's mount wrapper or switch to React Testing Library which is better than Enzyme for modern generation of React.

Please note that mount can render stateful functional components, but not able to access the state. These will fail:

mount(<Test/>).setState();
mount(<Test/>).state();
Related