Naresh Manthena
Naresh Manthena

Reputation: 159

How do I write state case for the state in react useState using Jest

I am new to Jest, I trying to write test case for state value , I am want to update the state value in test suite, any one can help in this. thanks.

Ex: My Component import React, {useState} from 'react';

    import Child from './Child';

    function Parent(props) {
      const [isFetching, setState] = useState(false);
      return (
        <div className="parent">
          <h1>Parent</h1>
        {isFetching ? 0 : 1}
        <Child called={setState} />
        { isFetching ? <div>
            <p>from  state true</p>
            <button onClick={clickmefn}>click me</button>
            </div>: null
        }
        </div>
      );
    }

    export default (Parent);

My Test suite which is failed due not found the element wrapper.find('p').text() unbale to find this because the is state false.

import Parent from './Parent';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
import { mount, shallow } from 'enzyme';

const setHookState = (newState) => jest.fn().mockImplementation((state) => [
    newState,
    (newState) => {}
 ])

const reactMock = require('react')
describe('ComponentWithHook component', () => {
    let wrapper
    beforeEach(() => {
     wrapper = shallow(<Parent/>)
    });
  it('should render itself', () => {
    const changeCounter = jest.fn();
    const handleClick = jest.spyOn(React, "useState");
    handleClick.mockImplementation(isFetching => [isFetching, changeCounter]);
    
    expect(wrapper.find('p').text()).toBe('from  state true');
  })

})

Upvotes: 1

Views: 1445

Answers (1)

lissettdm
lissettdm

Reputation: 13078

I recommend to do the test the more real as possible, and you can accomplish that without using an extra lib, just using react-dom and react-dom/test-utils.

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import Parent from './Parent';

    
describe("App Tests", () => {
  let container = null;

  beforeEach(() => {
    container = document.createElement("div");
    document.body.appendChild(container);
  });

  afterEach(() => {
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });

  it("should render itself", () => {
   act(async () => {
      render(
        <Parent/>,
        container
      );
    });

    const childElement = container.querySelector(`.child-element`); // get the child element
    act(() => {
      childElement.dispatchEvent( // distpach the action to update the state
       new MouseEvent("click", { bubbles: true })
     );
   });
    expect(container.querySelector('p')).toBeTruthy();
    expect(container.querySelector('p').textContent).toBe("from  state true");
  });
});

EDIT: // here you can find more info, https://reactjs.org/docs/testing-recipes.html

Upvotes: 1

Related Questions