我有一个像这样的自定义钩子:
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
没有做它正在做的事情,否则它不会更新?