【问题标题】:Setting state value coming from axios when using useState() and useEffect() in React在 React 中使用 useState() 和 useEffect() 时设置来自 axios 的状态值
【发布时间】:2020-12-08 21:32:07
【问题描述】:

当我运行此测试时,axios 调用被正确模拟,但setParticipant() 从未设置participant 变量的值。我猜这是因为它是异步的。如何在测试中断言之前“等待”setParticipant() 调用完成?

参与者.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>
  );
}

参与者-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")
  });
});

【问题讨论】:

  • 在示例中我取出了props.participantId 来简化它。现在没了。

标签: javascript reactjs axios react-testing-library


【解决方案1】:

鉴于您正在使用异步挂钩,请尝试在 act 前面添加 await 以应用已解决的承诺:

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

这在测试配方文档的data fetching 部分有简要介绍。

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2021-04-10
    • 2020-07-21
    • 2020-10-20
    • 2020-02-14
    • 1970-01-01
    • 2019-08-04
    • 2021-05-17
    相关资源
    最近更新 更多