【问题标题】:How can I test changing states in React?如何在 React 中测试不断变化的状态?
【发布时间】:2020-01-08 21:58:09
【问题描述】:

我是 React 新手,正在尝试使用 jest & testing-library/react 测试我的代码。

我制作了一个简单的选择框并在该框上触发了更改事件。 我想要的只是获得状态,但我仍然不知道如何获得它。

这是我的组件:

import React from "react";
import ReactDOM, { render } from "react-dom";
import NativeSelect from "@material-ui/core/NativeSelect";

const MyTest = () => {
  const [option, setOption] = React.useState("1");

  const handleChange = React.useCallback(e => {
    setOption(e.target.value);
  }, []);

  return (
    <div>
      <h3>selected : {option}</h3>
      <NativeSelect
        inputProps={{ "data-testid": "test-input" }}
        value={option}
        onChange={handleChange}
      >
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </NativeSelect>
    </div>
  );
};

export default MyTest;

这是测试:

import React from "react";
import { renderHook, act } from "@testing-library/react-hooks";
import { render, fireEvent } from "@testing-library/react";
import MyTest from "./MyTest";

test("should change state", () => {
  const { result } = renderHook(() => MyTest());

  let { getByTestId } = render(<MyTest />);
  const selectNode = getByTestId("test-input");
  expect(selectNode).not.toBeNull();

  act(() => {
    fireEvent.change(selectNode, { target: { value: "2" } });
  });

  expect(result.current.option).toBe("2");
});

codesandbox 在这里: https://codesandbox.io/s/distracted-wave-j5fed?fontsize=14

那么测试的错误信息是 : “比较两种不同类型的值。预期的字符串,但收到未定义。”

我猜“result.current.option”是获取状态的错误方式...... 如何获取组件的状态?

另外,根据我的搜索,可以使用 Enzyme 轻松测试道具和状态。

如果这是正确的,我应该使用 Enzyme 而不是 react-testing-library 来测试状态吗?

非常感谢。

【问题讨论】:

    标签: reactjs jestjs react-testing-library


    【解决方案1】:

    这两个是不同的对象:

    const { result } = renderHook(() =&gt; MyTest());

    let { getByTestId } = render(&lt;MyTest /&gt;);

    result.current.option 是未定义的,因为 result 是返回的组件而不是钩子函数。

    要么测试状态,要么测试渲染的组件。

    用于测试组件:

    在您的测试中应该是:expect(selectNode.value).toBe("2") 或者你从文档中关注这个:https://reactjs.org/docs/hooks-faq.html#how-to-test-components-that-use-hooks

    用于测试钩子的状态。您应该提取一个自定义钩子并像这样对其进行测试。

    来自https://github.com/testing-library/react-hooks-testing-library

    function useCounter() {
      const [count, setCount] = useState(0)
    
      const increment = useCallback(() => setCount((x) => x + 1), [])
    
      return { count, increment }
    }
    
    test('should increment counter', () => {
      const { result } = renderHook(() => useCounter())
    
      act(() => {
        result.current.increment()
      })
    
      expect(result.current.count).toBe(1)
    })
    

    【讨论】:

      猜你喜欢
      • 2021-06-03
      • 1970-01-01
      • 2017-11-26
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多