在某些情况下,您可以通过角色(或者不太理想的测试 ID)选择元素,然后断言所需属性是否存在,而不是依赖于本地 DOM,以代替全能的getBy
调用:
expect(screen.getByRole("textbox")).toHaveAttribute("name", "userName");
很遗憾,
screen.getByRole("textbox", {name: "userName"});
代码似乎并没有按照预期工作。请参考React测试库中的名称选项是什么?进行解释。
证明:
import React from "react";
import {render, screen} from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
describe("getByRole experiments", () => {
beforeEach(() => render(<input type="text" name="userName" />));
it("should work with a plain getByRole", () => {
expect(screen.getByRole("textbox"))
.toHaveAttribute("name", "userName");
});
it("will fail specifying {name: /userName/i}", () => {
screen.getByRole("textbox", {name: /userName/i});
});
it('will also fail specifying {name: "userName"}', () => {
screen.getByRole("textbox", {name: "userName"});
});
});
部分输出(name: "userName"
断言失败基本相同):
TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/userName/i`
Here are the accessible roles:
textbox:
Name "":
<input
name="userName"
/>
--------------------------------------------------
Ignored nodes: comments, <script />, <style />
<body>
<div>
<input
name="userName"
/>
</div>
</body>
另请参阅{{link1:React测试库:如何在自定义角色上使用getByRole}}。
name
的混淆。它是 ARIA 可访问名称,而不是name="userName"
属性。请参阅 What is the name option in react-testing-library?。 - ggorlen{name: /userName/i}
是无效的。 - ggorlen