升级到 React 17 后,addEventListener 向文档添加了无意的 selectionchange 事件

After upgrading to React 17, there are non-intentional selectionchange event added to document by addEventListener

提问人:Flora Liu 提问时间:11/11/2023 最后编辑:Flora Liu 更新时间:11/11/2023 访问量:20

问:

我正在使用 jest v27 和 @testing-library/react v12,我升级到了 React 17,addEventListener 向文档添加了无意的 selectionchange 事件。我根本没有使用这个事件。

最小可重现示例:

// App.test.tsx

import { render } from "@testing-library/react";
import App from "./App";

test("App", () => {
  it("test", async () => {
    const addSpyDoc = jest.spyOn(window.document, "addEventListener");
    render(<App />);

    // this expect would fail and show that it is called with 
    // 1: "selectionchange", [Function bound dispatchDiscreteEvent], false
    // 2: "selectionchange", [Function bound dispatchDiscreteEvent], true
    
   expect(addSpyDoc).not.toHaveBeenCalled();
  });
});


// App.tsx 

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
    </div>
  );
}

// index.tsx

import { render } from "react-dom";
import App from "./App";

const rootElement = document.getElementById("root");
render(<App />, rootElement);

以下是配置文件和package.json

// tsconfig.json

{
  "include": ["*"],
  "compilerOptions": {
    "baseUrl": ".",
    "lib": ["dom", "es2015"],
    "jsx": "react-jsx",
    "isolatedModules": true,
    "moduleResolution": "node",
    "module": "ESNext",
    "target": "ES6",
    "resolveJsonModule": true
  }
}

// .babelrc.json

{
  "sourceType": "unambiguous",
  "presets": [
    "@babel/preset-env",
    "@babel/preset-typescript",
    "@babel/preset-react"
  ],
  "plugins": []
}

// jest.config.ts

import type { Config } from "@jest/types";

export const sharedConfig: Config.InitialOptions = {
  verbose: true,
  preset: "ts-jest",
  testEnvironment: "jsdom",
};

// package.json

  "dependencies": {
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "ts-node": "^10.9.1",
    "ts-jest": "^27.1.3",
    "@babel/core": "^7.17.9",
    "@babel/preset-env": "^7.23.3",
    "@babel/preset-react": "^7.23.3",
    "@babel/preset-typescript": "^7.23.3",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "12.1.5",
    "@types/jest": "^27.4.1",
    "@types/node": "^17.0.25",
    "@types/react": "17.0.55",
    "@types/react-dom": "17.0.23",
    "babel-loader": "^8.2.4",
    "jest": "27.5.1",
    "typescript": "4.5.3"
  },
  "scripts": {
    "test": "jest test --env=jsdom"
  },

为了更易于运行,这里有两个带有 React 17 和 16 的沙盒。在 v16 中,没有向文档添加额外的事件。

https://codesandbox.io/s/jest-react-testing-library-forked-8cygdn?file=/src/App.test.tsx反应 17

https://codesandbox.io/s/jest-react-testing-library-forked-r4k6zh?file=/src/App.test.tsx反应 16

这种行为是意料之中的吗?添加此无意的 selectionchange 事件的原因是什么?

非常感谢您的帮助!

reactjs jestjs addeventlistener 反应测试库 jsdom

评论

0赞 ggorlen 11/11/2023
代码应该是问题本身中最小的可重现示例。沙盒链接会随着时间的推移而关闭,使资源对未来的访问者不太有用。谢谢!

答: 暂无答案