gpt4 book ai didi

reactjs - 如何使用 JEST、Enzyme 在 React 中测试自定义钩子(Hook)?

转载 作者:行者123 更新时间:2023-12-04 11:48:37 26 4
gpt4 key购买 nike

我有一个像下面这样的自定义钩子(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-utils
import 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com