简体   繁体   English

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

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

So i have this custom hook: (it just increase, decrease and reset)所以我有这个自定义钩子:(它只是增加,减少和重置)

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
    };
};

I would like to test it by calling decrease two time, but it does not do the same effect twice, if I just put decrease() once and value expected to be 99,it works and the test pass.我想通过调用 reduce 两次来测试它,但它不会两次做同样的效果,如果我只放一次 reduction() 并且值预计为 99,它可以工作并且测试通过。 But i was wondering if it is possible to call decrease() twice.但我想知道是否可以调用 reduction() 两次。 I leave the test below.我把测试留在下面。

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);
    });
});

Your issue is that you are treating state like it is synchronous, but it is not.您的问题是您将 state 视为同步的,但事实并非如此。

State does not update until a re-render happens. State 在重新渲染发生之前不会更新。

When you call decrease() twice, you are essentially saying:当您调用decrease()两次时,您实际上是在说:

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

No matter how many times you call it, the counter will only decrement by 1.不管你调用多少次,计数器只会减1。

This is because the counter state value doesn't change during the same render.这是因为counter state 的值在同一渲染期间不会改变。

To use the most up to date value when setting state, you need to change your set state to use a callback function:要在设置 state 时使用最新值,您需要更改设置 state 以使用回调 function:

setCounter(prev => prev - factor)

This will work as expected.这将按预期工作。

In general, you should always use a callback function when the new state value depends on the old state value.通常,当新的 state 值取决于旧的 state 值时,您应该始终使用回调 function。 In your case, the new value uses the old value, so you should be using a callback function.在您的情况下,新值使用旧值,因此您应该使用回调 function。

You should also change your increase function in the same way.您还应该以同样的方式更改您的increase function。

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

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