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

时间:2019-02-23 02:00:16

标签: reactjs jestjs react-testing-library

我仍在将我的酶测试转移到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;

使用Enzyme,我可以将状态手动设置为loadingStates键中的任何一个,并断言render conditional会进行适当的更改。

有没有一种方法可以在RTL中做到这一点?

1 个答案:

答案 0 :(得分:0)

使用RTL无法做到这一点。您不应该与组件内部进行交互。

这大致就是我测试您的组件的方式:

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

test('skeleton of a test', async () => {
  const people = [/* Put some mock people in here */]
  getPeople.mockResolveValueOnce({ 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()
})

如您所见,我没有检查App的内部状态。相反,我正在检查是否显示了一个加载微调器,然后检查了人们是否出现在屏幕上以及是否调用了API。

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