首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用找到一个元素(它在另一个页面上)?

如何使用找到一个元素(它在另一个页面上)?
EN

Stack Overflow用户
提问于 2022-06-28 15:55:03
回答 1查看 283关注 0票数 0

我需要找到这个元素,这个元素目前不存在,但它出现在app URL:(http://localhost:3000/step2)的另一个页面上,因为需要测试该元素。所以,我做了一种多步骤的形式,但是这些步骤是用React路由器实现的。

我知道当某些元素目前没有出现时,在这种情况下,我们应该使用findBy.,它将返回与已创建元素一起的承诺.

我根据文档编写了一段代码:

代码语言:javascript
复制
 const email = await screen.findByRole('textbox', {
            name: /email/i,
        })
        console.log(email)

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

代码语言:javascript
复制
Unable to find role="textbox"

简单的HTML如下所示:

代码语言:javascript
复制
<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/,以确保角色正确。

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

EN

回答 1

Stack Overflow用户

发布于 2022-06-28 16:10:56

您可以使用路由器来呈现组件,特别是用于测试的MemoryRouter

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

示例

代码语言:javascript
复制
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();
    },
  );
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72789666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档