如何找到一个元素,这是在另一个页面上,与React测试库?



我需要找到元素,它目前不存在,但呈现在应用程序URL的另一个页面上:(http://localhost:3000/step2),因为需要测试该元素。我做了一个多步骤表单,但这些步骤是用React Router实现的。

我知道当某些元素当前没有呈现时,在这种情况下,我们应该使用findBy…,它将返回一个带有创建元素的承诺…

我根据文档写了一个代码:

const email = await screen.findByRole('textbox', {
name: /email/i,
})
console.log(email)

但是我的终端显示这个消息错误:

Unable to find role="textbox"

纯HTML看起来像这样:

<div
class="MuiFormControl-root MuiFormControl-fullWidth MuiTextField-root css-wb57ya-MuiFormControl-root-MuiTextField-root"
><label
class="MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-shrink MuiInputLabel-outlined MuiFormLabel-root MuiFormLabel-colorPrimary MuiFormLabel-filled css-1kty9di-MuiFormLabel-root-MuiInputLabel-root"
data-shrink="true"
for="mui-3"
id="mui-3-label"
>Email</label>
<div
class="MuiOutlinedInput-root MuiInputBase-root MuiInputBase-colorPrimary MuiInputBase-fullWidth MuiInputBase-formControl css-md26zr-MuiInputBase-root-MuiOutlinedInput-root"
><input
aria-invalid="false"
name="email"
type="text"
class="MuiOutlinedInput-input MuiInputBase-input css-1t8l2tu-MuiInputBase-input-MuiOutlinedInput-input"
value="218855@ukr.net"
id="mui-3"
>
<fieldset
aria-hidden="true"
class="MuiOutlinedInput-notchedOutline css-1d3z3hw-MuiOutlinedInput-notchedOutline"
>
<legend class="css-1z7n62"><span>Email</span></legend>
</fieldset>
</div>
</div>

你可以复制我的片段的HTML代码并粘贴到这个资源:https://testing-playground.com/确保角色是正确的。

我做错了什么?如何找到所需的元素?

你可以用router来渲染组件,尤其是MemoryRouter,它是用来测试的。

我建议将initialEntry作为step1,模拟重定向到step2的代码,并等待看到电子邮件文本框。

例子
import { MemoryRouter, Route } from 'react-router-dom';
test('TEST_NAME',(fieldName: string) => {
render(
<MemoryRouter initialEntries={['/step1']}>
<YOUR_COMPONENT/>
</MemoryRouter>,
);
// write test logic 
// assert email is in the document.
expect(await screen.findByRole('textbox', {
name: /email/i,
})).toBeInTheDocument();
},
);

相关内容

最新更新