繁体   English   中英

在使用 hookRender() 和 act() 使用酶进行测试时,使用自定义钩子的相同 function 时出现问题

[英]Problems using the same function of a custom hook while testing with enzyme using hookRender() and act()

所以我有这个自定义钩子:(它只是增加,减少和重置)

import { useState } from 'react';
export const useCounter = (initialState = 1) => {

    const [counter, setCounter] = useState(initialState);
    const increase = (factor = 1) =>{
        setCounter(counter + factor);
    }
    const decrease = (factor = 1) =>{
        setCounter(counter - factor);
    }
    const reset = () =>{
        setCounter(initialState)
    }
    return {
        counter,
        increment,
        decrease,
        reset
    };
};

我想通过调用 reduce 两次来测试它,但它不会两次做同样的效果,如果我只放一次 reduction() 并且值预计为 99,它可以工作并且测试通过。 但我想知道是否可以调用 reduction() 两次。 我把测试留在下面。

import "@testing-library/jest-dom";
import { renderHook, act } from "@testing-library/react-hooks";
import { useCounter } from "../../hooks/useCounter";

describe("Test useCounter", () => {
    test("should decrease two times", () => {
        const { result, rerender } = renderHook(() => useCounter(100));
        const { decrease } = result.current;
        act(() => {
            decrease();
            decrease();
        });

        const { counter } = result.current;
        expect(counter).toBe(98);
    });
});

您的问题是您将 state 视为同步的,但事实并非如此。

State 在重新渲染发生之前不会更新。

当您调用decrease()两次时,您实际上是在说:

setCounter(100 - 1)
setCounter(100 - 1)

不管你调用多少次,计数器只会减1。

这是因为counter state 的值在同一渲染期间不会改变。

要在设置 state 时使用最新值,您需要更改设置 state 以使用回调 function:

setCounter(prev => prev - factor)

这将按预期工作。

通常,当新的 state 值取决于旧的 state 值时,您应该始终使用回调 function。 在您的情况下,新值使用旧值,因此您应该使用回调 function。

您还应该以同样的方式更改您的increase function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM