reactjs 如何解决testing-library-react中的“update was not wrapped in act()”警告?

5sxhfpxr  于 2022-11-22  发布在  React
关注(0)|答案(6)|浏览(161)

我正在使用一个会产生副作用的简单组件。我的测试通过了,但是我收到了Warning: An update to Hello inside a test was not wrapped in act(...).警告。
我也不知道waitForElement是否是编写此测试的最佳方式。

我的组件

export default function Hello() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      setPosts(response.data);
    }

    fetchData();
  }, []);

  return (
    <div>
      <ul>
        {
          posts.map(
            post => <li key={post.id}>{post.title}</li>
          )
        }
      </ul>
    </div>
  )
}

我的组件测试

import React from 'react';
import {render, cleanup, act } from '@testing-library/react';
import mockAxios from 'axios';
import Hello from '.';

afterEach(cleanup);

it('renders hello correctly', async () => {
  mockAxios.get.mockResolvedValue({
    data: [
        { id: 1, title: 'post one' },
        { id: 2, title: 'post two' },
      ],
  });

  const { asFragment } = await waitForElement(() => render(<Hello />));

  expect(asFragment()).toMatchSnapshot();
});
6kkfgxo0

6kkfgxo01#

更新的答案:

请参考下面的@mikaelrs评论。
不需要waitFor或waitForElement。你可以只使用findBy* 选择器,它返回一个可以等待的承诺。例如await findByTestId('list');

不建议使用的答案:

使用waitForElement是一种正确的方法,从docs:
等待,直到模拟的get请求承诺解决,组件调用setState并重新呈现。waitForElement等待,直到回调不抛出错误
以下是您的案例的工作示例:
index.jsx

import React, { useState, useEffect } from 'react';
import axios from 'axios';

export default function Hello() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      setPosts(response.data);
    };

    fetchData();
  }, []);

  return (
    <div>
      <ul data-testid="list">
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

index.test.jsx

import React from 'react';
import { render, cleanup, waitForElement } from '@testing-library/react';
import axios from 'axios';
import Hello from '.';

jest.mock('axios');

afterEach(cleanup);

it('renders hello correctly', async () => {
  axios.get.mockResolvedValue({
    data: [
      { id: 1, title: 'post one' },
      { id: 2, title: 'post two' },
    ],
  });
  const { getByTestId, asFragment } = render(<Hello />);

  const listNode = await waitForElement(() => getByTestId('list'));
  expect(listNode.children).toHaveLength(2);
  expect(asFragment()).toMatchSnapshot();
});

100%覆盖的单元测试结果:

PASS  stackoverflow/60115885/index.test.jsx
  ✓ renders hello correctly (49ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.jsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        4.98s

index.test.jsx.snapshot

// Jest Snapshot v1

exports[`renders hello correctly 1`] = `
<DocumentFragment>
  <div>
    <ul
      data-testid="list"
    >
      <li>
        post one
      </li>
      <li>
        post two
      </li>
    </ul>
  </div>
</DocumentFragment>
`;

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60115885

nwo49xxi

nwo49xxi2#

对我来说,解决办法是等待waitForNextUpdate

it('useMyHook test', async() => {
      const {
        result,
        waitForNextUpdate
      } = renderHook(() =>
        useMyHook(),
      );
      await waitForNextUpdate()
      expect(result.current).toEqual([])
    }
oxosxuxt

oxosxuxt3#

WaitFor对我很有效,我试着使用这里提到的findByTestId,但是我仍然得到同样的操作错误。
我的解决方案:

it('Should show an error message when pressing “Next” with no email', async () => {
const { getByTestId, getByText  } = render(
  <Layout buttonText={'Common:Actions.Next'} onValidation={() => validationMock}
  />
);

const validationMock: ValidationResults = {
  email: {
    state: ValidationState.ERROR,
    message: 'Email field cannot be empty'
  }
};

await waitFor(() => {
  const nextButton = getByTestId('btn-next');
  fireEvent.press(nextButton);
});

expect(getByText('Email field cannot be empty')).toBeDefined();
m3eecexj

m3eecexj4#

我有一个错误:

console.error
  Warning: A suspended resource finished loading inside a test, but the event was not wrapped in act(...).
  
  When testing, code that resolves suspended data should be wrapped into act(...):
  
  act(() => {
    /* finish loading suspended data */
  });
  /* assert on the output */
  
  This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act

密码:

test('check login link', async () => {
    renderRouter({ initialRoute: [home.path] });
    const loginLink = screen.getByTestId(dataTestIds.loginLink);
    expect(loginLink).toBeInTheDocument();
  
    userEvent.click(loginLink);
    const emailInput = screen.getByTestId(dataTestIds.emailInput);
    expect(emailInput).toBeInTheDocument();
}

我决定:

test('check login link', async () => {
  renderRouter({ initialRoute: [home.path] });
  const loginLink = screen.getByTestId(dataTestIds.loginLink);
  expect(loginLink).toBeInTheDocument();

  userEvent.click(loginLink);

  await waitFor(() => {
    const emailInput = screen.getByTestId(dataTestIds.emailInput);
    expect(emailInput).toBeInTheDocument();
  });
}

我刚刚在回调fn - waitFor()中进行了 Package
也许会对某人有用

cfh9epnr

cfh9epnr5#

slideshowp 2上面的答案很好,但是非常具体地针对您的特定示例。(他的答案似乎不起作用,因为它没有等待axios的承诺来解决;总是存在listtestid,但这很容易修复。)
如果您的代码发生了更改,例如,在找到listtestId之后,Assert运行,然后触发另一个useEffect,这将导致您不关心的状态更新,您将再次遇到相同的act问题。一个通用的解决方案是将render Package 在act中以确保在继续Assert和测试结束之前完成所有更新。这些Assert不需要waitFor任何东西。重写测试主体如下:

axios.get.mockResolvedValue({
  data: [
    { id: 1, title: 'post one' },
    { id: 2, title: 'post two' },
  ],
});
let getByTestId;
let asFragment;
await act(()=>{
  const component = render(<Hello />);
  getByTestId = component.getByTestId;
  asFragment = component.asFragment;
});
const listNode = getByTestId('list');
expect(listNode.children).toHaveLength(2);
expect(asFragment()).toMatchSnapshot();

(从测试库导入act。)
请注意,render被 Package 在act中,并且使用getBy*查找列表,这不是异步的!所有承诺解析都在getByTestId调用之前完成,因此在测试结束后不会发生状态更新。

wi3ka0sx

wi3ka0sx6#

这对我有用。

import React from 'react';
    import { render, waitFor } from '@testing-library/react';
    import App from './App';
    import { Loader } from './components';
    
     describe('App', () => {
          test('renders App component', () => {
          render(<React.Suspense fallback={<Loader open={true} backgroundColor="black" />}><App /></React.Suspense>)
            const el = document.querySelector('app')
            waitFor(() => { expect(sel).toBeInTheDocument() })
        
 });
});

相关问题