我正在使用一个有副作用的简单组件。我的测试通过了,但我收到警告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>
)
}
Run Code Online (Sandbox Code Playgroud)
我的组件测试
import React from 'react';
import {render, cleanup, act } from '@testing-library/react';
import mockAxios from …Run Code Online (Sandbox Code Playgroud) unit-testing reactjs jestjs react-testing-library testing-library
这是我的代码示例
<div class="dropdown" data-testid="dropdown">
<div class="option" data-testid="option">
<b>[AF]</b> Afghanistan
</div>
<div class="option" data-testid="option">
<b>[AL]</b> Albania
</div>
<div class="option" data-testid="option">
<b>[DZ]</b> Algeria
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我需要做的是通过文本访问第一个元素以触发 userEvent.selectOptions
const dropdown = getByTestId('dropdown');
userEvent.selectOptions(dropdown, screen.getByText('[AF] Afghanistan'))
Run Code Online (Sandbox Code Playgroud)
我得到的是:
TestingLibraryElementError:无法找到带有文本的元素:[AF] 阿富汗。这可能是因为文本被多个元素分解。在这种情况下,您可以为文本匹配器提供一个函数,以使您的匹配器更加灵活。
显然是因为我试图查询的文本被元素破坏了。
请注意,这不是一个选择/选项下拉列表,它没有任何可访问的角色,所以我只能通过 screen.getByText 查询它
React 测试库在渲染期间不会应用sxMaterial UI 组件的 props。
例如,我指定属性以在某些断点处隐藏元素。
<>
<AppBar
data-testid="mobile"
...
sx={{
display: { xs: "block", sm: "none" }
}}
>
MOBILE
</AppBar>
<AppBar
data-testid="desktop"
...
sx={{
display: { xs: "none", sm: "block" }
}}
>
DESKTOP
</AppBar>
</>
Run Code Online (Sandbox Code Playgroud)
在浏览器中一切都按预期工作。在 React 测试库中渲染时,我得到包含两个元素的结果。从样式上可以明显看出,它们是基本的,并且sx没有应用该属性。链接到codesandbox
import { ThemeProvider } from "@mui/material/styles";
import { screen, render } from "@testing-library/react";
import darkTheme from "./darkTheme";
import App from "./App";
describe("Demo", () => {
it("should have display props", () => { …Run Code Online (Sandbox Code Playgroud) Jest 遇到意外令牌
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how …Run Code Online (Sandbox Code Playgroud) 我的组件中有多个按钮,所有这些按钮都应该被禁用。
const buttons = screen.getAllByRole('button');
expect(ALL BUTTONS).toHaveAttribute('disabled'); // I want something like this.
Run Code Online (Sandbox Code Playgroud)
我们怎样才能以最方便的方式写这个呢?
javascript reactjs jestjs react-testing-library testing-library
我们注意到我们的单元测试执行速度非常慢,罪魁祸首似乎是getByRole查询按钮元素等。以下是今天给我们带来问题的查询示例:
userEvent.click(screen.getAllByRole('button', { name: 'Accept' })[0]);
Run Code Online (Sandbox Code Playgroud)
我们console.time()测量该查询的执行时间为 12782 毫秒。切换到getByText查询后需要 14 毫秒,这意味着getByRole花费了近 1000 倍的时间(!!!)。
我知道getByRole预计会运行得更慢,但这似乎有些极端。我在网上找到了一些线程,详细说明了某些测试如何花费了 5 倍的时间,但没有像这样的。作为选项添加hidden: true会加快速度,但速度不会太快。
我无法共享正在测试的代码,因为它是私有的。我不会将该组件描述为特别复杂,尽管它由一些较低级别的组件组成并使用模拟的网络请求。
是否有任何已知的原因导致像这样的查询运行缓慢,或者我们有什么方法可以在不牺牲所提供的信心的情况下加快执行速度getByRole?
我为选择编写了一个测试,并收到此警告。在我的测试中,我正在等待表演结束。为什么我会收到此错误?
警告:您似乎有重叠的 act() 调用,这是不支持的。在进行新的调用之前,请务必等待之前的 act() 调用。
test('Selection should be have the correct number of options', async () => {
const leftClick = { button: 0 };
const { options } = makeSUT();
const selection = screen.getByLabelText('MultiSelection');
// open all option
act(() => {
userEvent.click(selection, leftClick);
});
// await wait();
options.forEach(async (option, index) => {
if (index === 0) {
expect((await screen.findAllByText(option.label)).length).toEqual(1);
} else {
expect((await screen.findAllByText(option.label)).length).toEqual(1);
}
});
});
Run Code Online (Sandbox Code Playgroud)
谢谢
问题:UserEvent.type不工作。我有一个简单的测试,我得到了文本框,它可以工作,但是当尝试在该文本框中键入时,文本不会显示。
我见过的大多数类似问题的解决方案都是等待打字。我试过了,文本仍然不显示。
版本:
"jest": "^28.1.3",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "12.1.2",
"@testing-library/user-event": "^14.2.1",
Run Code Online (Sandbox Code Playgroud)
测试:
test('LoginPage should handle events properly', async () => {
render(<LoginPage />)
const textbox = screen.getByRole(/textbox/i)
await userEvent.type(textbox, 'test')
screen.debug(textbox)
})
Run Code Online (Sandbox Code Playgroud)
screen.debug()触发打字后的输出:
<textarea
placeholder="enter your private key here."
/>
Run Code Online (Sandbox Code Playgroud)
登录页面组件:
import { useHistory } from 'react-router-dom'
import { useContext, useState, useEffect } from 'react'
import { ABOUT_URL } from '../../config'
import LoadingCover from '../../components/loadingCover/loadingCover'
import LoadingButton from '../../components/loadingButton/loadingButton'
import UserContext from '../../context/User'
const LoginPage …Run Code Online (Sandbox Code Playgroud) 我已经开始在我的最新项目中使用 Next.js,我想对页面实现一些测试。我创建了一个_document文件,在其中设置了我想要使用的所有元标记,包括页面标题。
<html>
<InlineStylesHead />
<body>
<Main />
<NextScript />
<Head>
<title>testing title</title>
</Head>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
然后我设置测试来渲染此页面(应将其包含_document在其中)
它按预期工作(包括 SSR)。
然后我尝试使用react-testing-library和测试它jest
这是我的测试:
it('should render the title', () => {
render(<Page />);
waitFor(() => {
expect(document.title).toEqual('test title');
});
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,它给了我误报,而expect无论如何,block 都会给出真实的结果。我也尝试过Head直接在页面上设置,不幸的是,同样的问题。
您是否使用过任何其他技术来测试此类事物?谢谢!
reactjs jestjs next.js react-testing-library testing-library
我想知道是否将新的类名放入 html 组件中只是为了可读性和测试是否可以。假设我们有这样的情况:
class ComponentOne extends React.Component {
render(){
<div>
<div>
<div className="lower">
{sometext}
</div>
</div>
</div>
}
}
Run Code Online (Sandbox Code Playgroud)
这些类在这里只是为了提高浏览器的可读性以及更好地测试该组件。像这样 :
import { render } from '@testing-library/react'
it("Testing ComponentOne", ()=>{
const { container } = render(<Component/>)
const element = container.querySelector(".lower") // cleaner element searching
// testing element's text here
})
Run Code Online (Sandbox Code Playgroud)
在 React 中仅出于可读性/调试/测试目的使用“空”类是一个坏主意吗?在测试时查找元素的最佳方法是什么?
testing-library ×10
reactjs ×7
jestjs ×5
unit-testing ×5
testing ×3
next.js ×2
classname ×1
javascript ×1
material-ui ×1
token ×1