我有一个像下面这样的自定义钩子(Hook)
const useSum = (a = 1, b = 1) => {
const [sum, setSum] = useState(a + b);
useEffect(() => {
setSum(a + b);
}, [a, b]);
return sum;
}
我在我的 funcionat 组件中使用它const MyFuncComp = () => {
const sum = useSum(1, 2);
return (
<div>{sum}</div>
);
}
在测试用例中,我有这样的describe('Testing MyFuncComp', () => {
const myFuncComp = mount(<MyFuncComp />);
it('should have value of sum', () => {
const expected = '3';
const received = myFuncComp.find('div').text();
expect(received).toEqual(expected);
});
})
它永远不会执行“useState”或“useEffect”。接收到的值总是“未定义”;
最佳答案
我推荐你使用:@testing-library/react-hooks
import { renderHook } from '@testing-library/react-hooks';
describe('Testing MyFuncComp', () => {
it('should have value of sum', () => {
const myFuncComp = renderHook(() => useSum(1,2));
const expected = '3';
const received = myFuncComp.current;
expect(received).toEqual(expected);
});
})
此外,我认为您不需要 enzyme 或任何库来测试您的组件,您可以使用 react-dom 和 react-dom/test-utilsimport React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import MyFunComp from "./MyFunComp";
let container = null;
describe("Card component", () => {
beforeEach(() => {
// setup a DOM element as a render target
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
// cleanup on exiting
unmountComponentAtNode(container);
container.remove();
container = null;
});
it("Should render correctly", async () => {
await act(async () => {
render(<MyFunComp />, container);
});
const div = container.querySelector("div");
expect(div).toBeTruthy();
expect(div.textContent).toBe("123");
});
});
关于reactjs - 如何使用 JEST、Enzyme 在 React 中测试自定义钩子(Hook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65039773/