使用 react-testing-library 进行测试时,我可以手动触发状态更改吗?

jkt*_*vis 12 reactjs jestjs react-testing-library

我仍在将我的 Enzyme 测试转移到 react-testing-library 的过程中,我有一个相当常见的场景,当一个组件安装时,它会启动一个 Ajax 请求来获取一些数据。就在获取开始之前,它设置一些状态值以指示它正在加载,这反过来呈现一个微调器。完成后,状态将更新为数据,并在适当的情况下将“loadingState”设置为“Completed”或“Failed”。

import React, { useEffect, useState } from "react";
import { SwapSpinner } from "react-spinners-kit";
import styled from "styled-components";
import * as R from "ramda";

import { getPeople } from "./getPeople";

const FlexCenter = styled.div`
  height: 250px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const loadingStates = {
  notStarted: "notStarted",
  isLoading: "isLoading",
  success: "success",
  failure: "failure"
};

function App() {
  const [people, setPeople] = useState([]);
  const [isLoading, setLoading] = useState(loadingStates.notStarted);

  useEffect(() => {
    setLoading(loadingStates.isLoading);
    getPeople()
      .then(({ results }) => {
        setPeople(results);
        setLoading(loadingStates.success);
      })
      .catch(error => {
        setLoading(loadingStates.failure);
      });
  }, []);

  return (
    <div>
      {R.cond([
        [
          R.equals(loadingStates.isLoading),
          () => (
            <FlexCenter data-testid="spinner">
              <SwapSpinner />
            </FlexCenter>
          )
        ],
        [
          R.equals(loadingStates.success),
          () => (
            <ul data-testid="people-list">
              {people.map(({ name }) => (
                <li key={name}>{name}</li>
              ))}
            </ul>
          )
        ],
        [R.equals(loadingStates.failure), <div>An error occured</div>]
      ])(isLoading)}
    </div>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

使用 Enzyme,我可以手动将状态设置为任何一个loadingStates键,并断言渲染条件呈现适当的更改。

有没有办法在 RTL 中做到这一点?

Gio*_*Gpx 12

你不能用 RTL 做到这一点。您不应该与组件的内部交互。

这大致是我将如何测试您的组件:

import { getPeople } from "./getPeople";
jest.mock('./getPeople')

test('skeleton of a test', async () => {
  const people = [/* Put some mock people in here */]
  getPeople.mockResolvedValueOnce({ results: people })
  render(<App />)

  expect(/* Somehow get the loading spinner */).toBeInTheDocument()

  await wait(() => expect(/* Here you check that the people is on the page */).toBeInTheDocument())

  // We also check that the API gets called
  expect(getPeople).toHaveBeenCalledOnce()
  expect(getPeople).toHaveBeenCalledWith()
})
Run Code Online (Sandbox Code Playgroud)

如您所见,我不是在检查App. 相反,我正在检查是否显示了一个加载微调器,然后人们出现在屏幕上并且 API 被调用。

此测试更可靠,因为您正在测试用户将看到的内容,而不是实现细节。