首页 > 解决方案 > 何时使用 waitForNextUpdate 而不是 act + jest.advanceTimersByTime?

问题描述

在advanced-hooks#async文档中有一个示例。

我对如何waitForNextUpdate工作感到困惑。我做了两个测试用例来比较waitForNextUpdateact()+ jest.advanceTimersByTime()

index.ts

import { useState, useCallback } from 'react';

export function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);
  const increment = () => setCount((x) => x + 1);
  const incrementAsync = useCallback(() => setTimeout(increment, 100, [increment]);
  const reset = useCallback(() => setCount(initialValue), [initialValue]);
  return { count, increment, incrementAsync, reset };
}

index.test.ts

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

jest.setTimeout(5 * 1000);

describe('waitForNextUpdate  V.S. jest-advancedTimersByTime', () => {
  test('should pass by using jest.advancedTimersByTime', () => {
    jest.useFakeTimers();
    const { result } = renderHook(() => useCounter());
    result.current.incrementAsync();
    act(() => {
      jest.advanceTimersByTime(100);
    });
    expect(result.current.count).toBe(1);
    jest.useRealTimers();
  });

  test('should pass by using waitForNextUpdate', async () => {
    const { result, waitForNextUpdate } = renderHook(() => useCounter());
    result.current.incrementAsync();
    await waitForNextUpdate();
    expect(result.current.count).toBe(1);
  });
});

测试结果:

 PASS  issues/waitForNextUpdate-vs-jest-advancedTimersByTime/index.test.ts
  waitForNextUpdate  V.S. jest-advancedTimersByTime
    ✓ should pass by using jest.advancedTimersByTime (13 ms)
    ✓ should pass by using waitForNextUpdate (107 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.373 s, estimated 14 s

两个测试用例都通过了。我发现的唯一区别是,如果我增加setTimeoutto的延迟1000 * 10,使用的测试用例waitForNextUpdate将失败。

// useCounter
//...
const incrementAsync = useCallback(() => setTimeout(increment, 1000 * 10), [increment]);
//...
// first test case
// ...
jest.advanceTimersByTime(1000 * 10);
// ...
 FAIL  issues/waitForNextUpdate-vs-jest-advancedTimersByTime/index.test.ts (10.554 s)
  waitForNextUpdate  V.S. jest-advancedTimersByTime
    ✓ should pass by using jest.advancedTimersByTime (19 ms)
    ✕ should pass by using waitForNextUpdate (1006 ms)

  ● waitForNextUpdate  V.S. jest-advancedTimersByTime › should pass by using waitForNextUpdate

    Timed out in waitForNextUpdate after 1000ms.

      at waitForNextUpdate (node_modules/@testing-library/react-hooks/lib/core/asyncUtils.js:102:13)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        11.112 s

waitForNextUpdate那么和 和act()+有什么区别jest.advanceTimersByTime()?什么样的场景我只能使用waitForNextupdate而不是act()+ jest.advanceTimersByTime()

包版本:

"@testing-library/react-hooks": "^5.0.0",
"jest": "^26.6.3",
"react": "^16.14.0"

标签: reactjsreact-hooksjestjsreact-hooks-testing-library

解决方案


推荐阅读