使用行为不会更新状态吗?

时间:2019-08-01 18:29:52

标签: react-hooks react-testing-library react-hooks-testing-library

我有一个像这样的自定义钩子:

import { useState } from 'react';

export default function useOpenClose(initial = false) {
    const [isOpen, setOpen] = useState(initial);

    const open = () => { setOpen(true); }
    const close = () => { setOpen(false); }

    return [isOpen, { open, close } ];
}

对于我的测试,我有这样的东西:

import { renderHook, act } from '@testing-library/react-hooks';
import useOpenClose from './useOpenClose';

describe('useOpenClose', () => {
    const { result: { current } } = renderHook(() => useOpenClose());
    const [isOpen, { open, close }] = current;

    test('Should have an open function', () => {
        expect(open).toBeInstanceOf(Function)
    });

    test('Should have an open function', () => {
        expect(close).toBeInstanceOf(Function)
    });

    test('Should have initial value of false', () => {
        expect(isOpen).toBe(false);
    });

    test('Should update value to true', () => {
        act(() => open());
        console.log(isOpen)
    })
});

在测试“应将值更新为true”的地方,当我登录isOpen时,它保持为false。我不完全确定为什么除非act没有做它正在做的事情,否则它不会更新?

0 个答案:

没有答案