React/Jest钩子测试,状态不总是更新

nzrxty8p  于 2024-01-04  发布在  Jest
关注(0)|答案(1)|浏览(161)

组件状态和功能

const [eventList, setEventList] = useState(events)
 const toggleSelect = (event: CalendarEventType):void => {
        event.selected = !event.selected
 }

 const addEvent = (event: CalendarEventType): void => {
    event.id = uuid()
    setEventList(prevState => [...prevState, event])
 }

字符串
测试

const {result} = renderHook((initialProps) => useCalendarEvent(initialProps), {initialProps: exampleEvent})

describe('Event management', () => {
    test('Select and unselect event', async () => {
        result.current.toggleSelect(result.current.eventList[0])
        expect(result.current.eventList[0].selected).toBeTruthy()
    })
    test('Add event', async () => {
        await act(async () => {
            result.current.addEvent({title: 'TestAdd', start: new Date()})
        })
        expect(result.current.eventList).toHaveLength(2)
    })
    test('log', () => {
        console.log(result.current.eventList)
    })
})


如果我运行这些测试,第二个测试会失败,console.log会返回一个事件,但是如果我把“Add event”的内容放在第一个测试函数中,它就能工作。
否则,如果我把“Add event”测试放在“Select and unselect event”测试之前,也可以工作,但我希望能够在添加事件之前和之后进行测试。

5f0d552i

5f0d552i1#

您正在使用await act(await c()=> {...})来处理异步addEvent函数。

describe('Event management', () => {
  test('Add event', async () => {
    await act(async () => {
      result.current.addEvent({ title: 'TestAdd', start: new Date() });
    });
    expect(result.current.eventList).toHaveLength(2);
  });

  test('Select and unselect event', () => {
    act(() => {
      result.current.toggleSelect(result.current.eventList[0]);
    });
    expect(result.current.eventList[0].selected).toBeTruthy();
  });

  test('log', () => {
    console.log(result.current.eventList);
  });
});

字符串

相关问题