簡體   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