gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:35:59 27 4
gpt4 key购买 nike

我正在使用一个具有副作用的简单组件。我的测试通过了,但是我得到了警告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();
});

最佳答案

更新的答案:
请参阅下面的@mikaelrs评论。

No need for the waitFor or waitForElement. You can just use findBy* selectors which return a promise that can be awaited. e.g await findByTestId('list');



不建议使用的答案:
从文档中使用 waitForElement是正确的方法:

Wait until the mocked get request promise resolves and the component calls setState and re-renders. waitForElement waits until the callback doesn't throw an error


这是您的情况的工作示例: 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

关于reactjs - 如何解决testing-library-react中的 “update was not wrapped in act()”警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60115885/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com