【发布时间】:2021-11-17 02:49:08
【问题描述】:
我正在尝试为我的组件编写测试代码,该组件使用自定义挂钩将逻辑与视图分开
问题是我似乎无法在测试中实际模拟这个自定义钩子。
以下是我尝试做的代码示例:
// 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 似乎没有任何作用。 请帮忙
【问题讨论】:
标签: reactjs jestjs react-hooks