查询无效名称后的警告文本

时间:2020-03-25 21:24:46

标签: reactjs react-testing-library

我对React Testing Library还是很陌生,并试图通过一个简单的测试。如果用户提交的表单的名称字段为空白,则会出现警告消息,提示“名称字段不能为空”。此消息会按预期显示在浏览器中,并且我的测试通过。

  it("When the create button is pressed, if the input field is empty, prevent the user from being added", async () => {
    const createUserWithBlankName = render(<CreateUserModal/>);

    await wait(() => fireEvent.click(createUserWithBlankName.getAllByText("Create")[1]));
    expect(createUserWithBlankName.getAllByText("Name field cannot be empty")).toBeTruthy();
  });

尽管测试通过了,但我想知道是否有更好的方法来修复fireEvent。到目前为止,它有点怪异,因为“创建”一词出现了两次(第一个出现在段落中,第二个出现在“创建”按钮中)。有没有更好的方法来重构此测试?

我尝试使用getByRole,但是{ name: "Create" }无法分配给'ByRoleOptions'类型的参数。

    await wait(() => fireEvent.click(createUserWithBlankName.getByRole("button", { name: "Create" }));

0 个答案:

没有答案