测试时,导致 React 状态更新的代码应该被包装成行为

dag*_*da1 15 reactjs react-testing-library

我有这个测试:

import {
  render,
  cleanup,
  waitForElement
} from '@testing-library/react'

const TestApp = () => {
  const { loading, data, error } = useFetch<Person>('https://example.com', { onMount: true });

  return (
    <>
      {loading && <div data-testid="loading">loading...</div>}
      {error && <div data-testid="error">{error.message}</div>}
      {data && 
        <div>
          <div data-testid="person-name">{data.name}</div>
          <div data-testid="person-age">{data.age}</div>
        </div>
      }
    </>
  );
};

  describe("useFetch", () => {
    const renderComponent = () => render(<TestApp/>);

    it('should be initially loading', () => {
      const { getByTestId } = renderComponent();

      expect(getByTestId('loading')).toBeDefined();
    })
  });
Run Code Online (Sandbox Code Playgroud)

测试通过,但我收到以下警告:

警告:测试中 TestApp 的更新未包含在 act(...) 中。

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser
    in TestApp
Run Code Online (Sandbox Code Playgroud)

console.error node_modules/react-dom/cjs/react-dom.development.js:506 警告:测试中 TestApp 的更新未包含在 act(...) 中。

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser
    in TestApp
Run Code Online (Sandbox Code Playgroud)

sug*_*ith 55

尝试在“await waitFor()”内断言 - 为此,您的 it() 函数应该是异步的

it('should be initially loading', async () => {
  const { getByTestId } = renderComponent();

  await waitFor(() => {
    expect(getByTestId('loading')).toBeDefined();
  });
});
Run Code Online (Sandbox Code Playgroud)

保持冷静和快乐的编码


Ogg*_*las 17

关键是要await act然后使用async箭头功能。

await act( async () => render(<TestApp/>));
Run Code Online (Sandbox Code Playgroud)

来源:

/sf/answers/4188765941/

  • 如果您投反对票,请评论原因。否则很难改进答案 (5认同)
  • 该来源使用的是酶安装,但这里的帖子使用的是反应测试库,我个人尝试过但没有成功 (2认同)

Piy*_*rin 8

尝试在 act 中使用 wait

import { act } from 'react-dom/test-utils';
await act(async () => {
            wrapper = mount(Commponent);
            wrapper.find('button').simulate('click');
        });
Run Code Online (Sandbox Code Playgroud)