gpt4 book ai didi

reactjs - 使用自定义 Hook 在组件上用 Jest 进行测试

转载 作者:行者123 更新时间:2023-12-05 05:56:02 24 4
gpt4 key购买 nike

我正在尝试为我的组件编写测试代码,该代码使用自定义 Hook 将逻辑与 View 分开

问题是无论出于何种原因,我似乎都无法在测试中实际模拟此自定义 Hook 。

以下是我正在尝试做的代码示例:


// click-a-button.tsx

import {useClickAButton} from "./hooks/index";

export const ClickAButton = () => {
const { handleClick, total } = useClickAButton();
return <button onClick={handleClick}>{total}</button>;
}

// hooks/use-click-a-button.tsx

import React, {useCallback, useState} from 'react';

export const useClickAButton = () => {
const [total, setTotal] = useState<number>(0);
const handleClick = useCallback(() => {
setTotal(total => total + 1);
}, []);
return {
handleClick,
total,
};
}

// click-a-button.test.tsx

import * as React from 'react';
import {act} from "react-dom/test-utils";
import {render} from "@testing-library/react";
import {useClickAButton} from './hooks/index'
import {ClickAButton} from "./index";

const hooks = { useClickAButton }

test('it runs with a mocked customHook',() => {
const STATE_SPY = jest.spyOn(hooks, 'useClickAButton');
const CLICK_HANDLER = jest.fn();

STATE_SPY.mockReturnValue({
handleClick: CLICK_HANDLER,
total: 5,
});

const component = render(<ClickAButton />);
expect(component.container).toHaveTextContent('5');
act(() => {
component.container.click();
});
expect(CLICK_HANDLER).toHaveBeenCalled();
})

运行测试时,没有满足任何期望。上下文变为 0 而不是模拟的 5,并且永远不会调用 CLICK_HANDLER。

总而言之,jest.spyon 似乎没有效果。请帮忙

最佳答案

看来我自己找到了答案。

// right after imports in test file    
jest.mock('./hooks')

就这样吧!

关于reactjs - 使用自定义 Hook 在组件上用 Jest 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69304498/

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