【问题标题】:Testing with jest on component with custom hook使用自定义钩子在组件上开玩笑测试
【发布时间】: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


    【解决方案1】:

    看来我自己找到了答案。

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

    就是这样!

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2017-11-01
      • 2019-11-10
      • 2021-10-09
      • 2019-09-25
      • 1970-01-01
      • 2018-06-02
      • 2017-07-13
      • 1970-01-01
      相关资源
      最近更新 更多