简体   繁体   中英

Setting state value coming from axios when using useState() and useEffect() in React

When I run this test the axios call is mocked correctly but setParticipant() never sets the value of the participant variable. I'm guessing it's because it's asynchronous. How do I "wait" for the setParticipant() call to complete before asserting in the test?

participant.tsx

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function EditParticipant(props) {
  const [participant, setParticipant] = useState(null)
  useEffect(() => {
      axios.get(`/api/participants`).then(response => {
        console.log(response.data)        // prints fine
        setParticipant(response.data)
      });
  }, []);

  return (
    <div>
      {participant ?   // always null
        <p>{participant.name}</p>           
        : ''
      }
    </div>
  );
}

participant-spec.tsx

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

import MockAdapter from 'axios-mock-adapter';
import { EditParticipant } from './participant-edit';

const mock = new MockAdapter(require('axios'));

describe('<Participant/>', () => {
  let container
  beforeEach(() => {
    container = document.createElement("div");
    document.body.appendChild(container);
  });
  afterEach(() => {
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });

  it('show bob', async () => {
    mock.onGet("/api/participants").reply(200, {name: "bob" });
    act(() => {
      render(<EditParticipant />, container);
    });
    expect(container.textContent).toContain("Bob")
  });
});

Given you are using async hooks try adding await in front of act to apply resolved promises:

it('show bob', async () => {
  mock.onPost("/api/participants").reply(200, {name: "bob" });
  await act(async () => {
    render(<EditParticipant />, container);
  });
  expect(container.textContent).toContain("Bob")
});

This is covered briefly in the data fetching portion of the testings recipes documentation.

Hopefully that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM