React Testing Library中Select下拉框选项测试指南

本文详细探讨了在React Testing Library中测试下拉框是常见的ui组件,其测试对于确保用户交互的正确性至关重要。react testing library (rtl) 旨在模拟用户行为,并鼓励开发者测试组件的最终用户可访问状态。然而,在测试

一个常见的误区是试图通过检查DOM元素的HTML属性(如hasAttribute('selected'))来判断一个

2. 常见测试陷阱与不推荐的实践

在尝试测试

2.1 使用userEvent.selectOptions并检查HTML属性

import React from "react";
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

test("Can Select Item - Incorrect Assertion", async () => {
  const user = userEvent.setup();

  const screen = render(
    
  );

  await user.selectOptions(screen.getByTestId("test"), "Hey");
  // 错误示范:检查hasAttribute('selected')可能无法反映真实状态
  expect(screen.getByTestId("Hey").hasAttribute("selected")).toBeTruthy(); 
});

上述测试中,即使userEvent.selectOptions成功触发了选择事件,screen.getByTestId("Hey").hasAttribute("selected")也可能返回false,导致测试失败。这是因为selected HTML属性在某些浏览器或测试环境中可能不会被DOM动态添加或移除,而JavaScript的selected属性才是可靠的指示器。

2.2 使用fireEvent.select并检查HTML属性

类似地,直接使用fireEvent.select来触发选择事件,然后检查HTML属性也会遇到同样的问题:

import React from "react";
import { fireEvent, render } from "@testing-library/react";

test("Can Select Item with fireEvent - Incorrect Assertion", async () => {
  const screen = render(
    
  );

  fireEvent.select(screen.getByTestId("test"), { target: { value: "1" } });
  // 错误示范:同样是检查hasAttribute('selected')
  expect(screen.getByTestId("Hey").hasAttribute("selected")).toBeTruthy();
});

尽管fireEvent.select成功模拟了选择事件,hasAttribute("selected")的检查依然是不可靠的,因为它依赖于HTML属性而非元素的实际JavaScript状态。

3. 正确的测试方法:模拟事件并检查selected属性

要正确测试

  1. 使用fireEvent.select或userEvent.selectOptions来模拟用户选择事件。
  2. 通过访问

以下是实现这一目标的推荐方法:

import React from "react";
import { fireEvent, render } from "@testing-library/react";

// 定义一个接口,用于更清晰地表示选项的状态
export interface KeyValuePair {
  value: string;
  selected: boolean;
}

it("should correctly set selected option in a dropdown", () => {
  // 渲染包含select和option元素的组件
  const { getByTestId, getAllByTestId } = render(
    
  );

  // 1. 模拟用户选择事件
  // 使用 fireEvent.select 触发 select 元素的 change 事件
  // target.value 应设置为要选中的 option 的 value
  fireEvent.select(getByTestId("select"), { target: { value: "1" } });

  // 2. 获取所有 option 元素并检查其选中状态
  // getAllByTestId 返回一个数组,确保获取所有具有相同 data-testid 的元素
  let options = getAllByTestId("select-option") as HTMLOptionElement[];

  // 3. 过滤出所有被选中的 option
  const values = options
    .map(
      (e) =>
        ({
          value: e.value,
          selected: e.selected, // 关键:检查 option 元素的 JavaScript 'selected' 属性
        } as KeyValuePair)
    )
    .filter((x) => x.selected);

  // 4. 执行断言
  // 确保只有一个选项被选中
  expect(values).toHaveLength(1);
  // 确保被选中的选项的 value 是我们期望的
  expect(values[0].value).toBe("1");
});

代码解析:

  1. fireEvent.select(getByTestId("select"), { target: { value: "1" } });: 这行代码模拟了用户在
  2. getAllByTestId("select-option"): 获取所有带有data-testid="select-option"的
  3. e.selected: 这是核心所在。HTMLOptionElement对象有一个selected属性,它是一个布尔值,准确地指示该选项当前是否被选中。这是验证选项状态的可靠方式,因为它直接反映了DOM元素的JavaScript状态,而不是可能不一致的HTML属性。
  4. filter((x) => x.selected): 过滤出所有selected属性为true的选项。
  5. expect(values).toHaveLength(1): 断言只有一个选项被选中,符合单选下拉框的预期行为。
  6. expect(values[0].value).toBe("1"): 断言被选中的选项的value是"1",验证了我们期望的选项确实被选中。

4. 总结与最佳实践

在React Testing Library中测试

  • 模拟用户行为:使用fireEvent.select或userEvent.selectOptions来触发选择事件。userEvent通常更接近真实用户交互,但对于简单的select事件,fireEvent.select也完全适用。
  • 检查JavaScript属性,而非HTML属性:在验证
  • 明确断言:通过过滤出所有选中的选项并检查其数量和值,可以对下拉框的选择行为进行清晰且健壮的断言。
  • 考虑默认选项:如果你的

遵循这些指南,你将能够编写出更稳定、更准确的React Testing Library测试,确保你的