Search code examples
reactjsunit-testingaxiosjestjsuse-effect

Unit Testing with Jest and React - Axios Get Inside useEffect


How do I write a unit test in Jest for the initializePlayers function inside the useEffect? Test if the call is working?

export default function App() {

...

  useEffect(() => {
    const initializePlayers = async () => {
      await axios.get(url)
      .then(async res=> {
        const activePlayers = res.data.filter(p => p.active === true);
        setPlayers(activePlayers);
      }).catch(err => {
        console.log(err);
      })
    }

    initializePlayerPool();
  }, []);

Solution

  • Please try this example.

    import React from "react";
    import { mount, shallow } from "enzyme";
    import axios from "axios";
    import { act } from "react-dom/test-utils";
    import App from "./App";
    jest.mock("axios");
    
    // mock data
    const url= "YOUR_URL",
       
    describe("App test", () => {
      let wrapper;
    
      // clear all mocks
      afterEach(() => {
        jest.clearAllMocks();
      });
    
      test("load app", async () => {
        // mock axios promise
        await act(async () => {
          await axios.get.mockImplementationOnce(() => Promise.resolve(url));
          wrapper = mount(<App />);
        });
    
        wrapper.update();
        await expect(axios.get).toHaveBeenCalledTimes(1);
      });
    });