使用useState对内部状态进行React Hook测试

时间:2020-04-21 04:43:21

标签: reactjs jestjs react-hooks enzyme

我一直在研究大量资源,以通过使用带有React Hook的useState来测试内部状态,但仍然找不到满意的答案,一些测试用例正在从mount或{{1 }}会显示在UI端,但不会从组件的内部状态(shallow)显示,如果组件未在UI端公开状态值,该怎么办,例如:

useState

如何编写测试用例进行测试

1)安装组件后,我的内部状态const TestComponent = () => { const [count, setCount] = React.useState(0); return ( <span> <button id="count-up" type="button" onClick={() => setCount(count + 1)}>Count Up</button> </span> ); } 会被初始化为0吗?

2)当组件模拟按钮count上的onClick事件时,应该调用我的count-up并且内部状态setCount应该变成1?

1 个答案:

答案 0 :(得分:1)

对于一个简单的测试示例,您可以在React上使用check来查看组件是否调用了jest.spyOn钩子:

setState

您还可以将import React from "react"; import App from "./app"; import Enzyme, { shallow } from "enzyme"; import Adapter from "enzyme-adapter-react-16"; Enzyme.configure({ adapter: new Adapter() }); describe("App", () => { it("should call setState with initial values on component mount", () => { const mockSetState = jest.spyOn(React, "useState"); shallow(<App />); expect(mockSetState).toHaveBeenCalledTimes(1); expect(mockSetState).toHaveBeenCalledWith(5); }); }); 移到一个单独的文件中并将其用作自定义钩子(可能是不必要的层,所以取决于您)

useState
// useCounter.js
import { useState, useCallback } from "react";

const useCounter = initialValue => {
  const [count, setValue] = useState(initialValue);
  const setCount = useCallback(x => setValue(x), []);
  return { count, setCount };
};

export default useCounter;

然后可以对“自定义”挂钩进行测试:

// usage: app.js
function App() {
  const { count, setCount } = useCounter(5);
  return (
    <div className="App">
      <h1>Testing React Hooks</h1>
      <p>{count}</p>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

在代码沙箱上的工作示例

Edit Testing React Hooks