reactjs 基本用户事件,selectOptions不工作

1szpjjfi  于 2023-04-29  发布在  React
关注(0)|答案(1)|浏览(82)

我有一个非常简单的下拉菜单组件,我想用@testing-library测试。

组件:

const DropdownMenu = () => {
  return (
    <div className="dropdown-menu__container">
      <select id="selectCity">
        <option>Mars</option>
        <option>Saturn</option>
        <option>Venus</option>
      </select>
    </div>
  );
};

测试

it("should call handleTestNameChange with the new value when the selection changes", () => {
    render(<DropdownMenu />);
    const selectElement = screen.getByRole("combobox");
    console.log("before select options ", selectElement.value);
    userEvent.selectOptions(selectElement, "Saturn");
    expect(selectElement).toHaveValue("Saturn");
  });

但它并不像预期的那样工作,请参见痕迹:

控制台结果

Console

    console.log
      before select options  Mars

      at Object.<anonymous> (src/components/batchrec/dropdown-menu/dropdown-menu.test.js:39:13)

  ● DropdownMenu component › should call handleTestNameChange with the new value when the selection changes

    expect(element).toHaveValue(Saturn)

    Expected the element to have value:
      Saturn
    Received:
      Mars

      39 |     console.log("before select options ", selectElement.value);
      40 |     userEvent.selectOptions(selectElement, "Saturn");
    > 41 |     expect(selectElement).toHaveValue("Saturn");
         |                           ^
      42 |   });
      43 | });
      44 |

问题:

如何使这个超级基础测试按预期工作?如何使selectOptions实际上选择该选项?

配置

"dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "date-fns": "^2.29.3",
    "react": "^18.2.0",
    "react-dnd": "^16.0.1",
    "react-dnd-html5-backend": "^16.0.1",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.9.0",
    "react-scripts": "5.0.1",
    "recharts": "^2.5.0",
    "sass": "^1.62.0",
    "tachyons": "^4.12.0",
    "web-vitals": "^2.1.4"

  "devDependencies": {
    "@babel/core": "^7.21.4",
    "@babel/plugin-transform-modules-commonjs": "^7.21.2",
    "@babel/preset-env": "^7.21.4",
    "@testing-library/user-event": "^14.4.3",
    "babel-jest": "^29.5.0"
  }
yhuiod9q

yhuiod9q1#

阅读文档有帮助。....
https://testing-library.com/docs/user-event/utility/

it("should call handleTestNameChange with the new value when the selection changes", async () => {
    render(<DropdownMenu />);
    const selectElement = screen.getByRole("combobox");
    console.log("before select options ", selectElement.value);
    await userEvent.selectOptions(selectElement, "Saturn");
    expect(selectElement).toHaveValue("Saturn");
  });

相关问题