我一直在研究大量资源以通过使用带有React Hook的useState来测试内部状态,但仍然找不到满意的答案,一些测试用例正在从mount
或shallow
抓取期望值,这将是在UI端显示但不在组件的内部状态(useState
)中显示,如果组件未在UI端公开状态值,该怎么办,例如:
const TestComponent = () => {
const [count, setCount] = React.useState(0);
return (
<span>
<button id="count-up" type="button" onClick={() => setCount(count + 1)}>Count Up</button>
</span>
);
}
如何编写测试用例进行测试
1)装入组件时,我的内部状态count
将初始化为0?
2)当组件模拟按钮onClick
上的count-up
事件时,应该调用我的setCount
,而我的内部状态count
应该变成1?
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>
);
}
然后您可以对“自定义”挂钩进行测试:
import { renderHook, act } from "@testing-library/react-hooks"; import useCounter from "./useCounter"; test("should increment counter", () => { const { result } = renderHook(() => useCounter(0)); act(() => { result.current.setCount(1); }); expect(result.current.count).toEqual(1); });
在代码沙箱上的工作示例