没有为 ts-jest 和 puppeteer 定义浏览器

browser not defined for ts-jest and puppeteer

我正在尝试使用 puppeteer 为我的 typescript create react app 创建 snapshot-tests。使用 jest 进行定期测试工作正常,但是一旦我尝试使用 浏览器 创建快照并且必须使用 browser 我的 .test.ts 文件中的变量 我被告知 browser is not defined.

我似乎无法解决这个问题,尽管我已经尝试解决这个问题几个小时了。

作为参考,这里是我的 package.json 文件中的笑话设置:

  "jest": {
"preset": "jest-puppeteer-preset",
"collectCoverageFrom": [
  "src/**/*.{js,jsx,ts,tsx}"
],
"setupFiles": [
  "<rootDir>/config/polyfills.js"
],
"testMatch": [
  "<rootDir>/src/**/__tests__/**/*.(j|t)s?(x)",
  "<rootDir>/src/**/?(*.)(spec|test).(j|t)s?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
  "^.+\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
  "^.+\.tsx?$": "<rootDir>/config/jest/typescriptTransform.js",
  "^.+\.css$": "<rootDir>/config/jest/cssTransform.js",
  "^(?!.*\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
  "[/\\]node_modules[/\\].+\.(js|jsx|mjs|ts|tsx)$"
],
"moduleNameMapper": {
  "^react-native$": "react-native-web"
},
"moduleFileExtensions": [
  "web.ts",
  "ts",
  "web.tsx",
  "tsx",
  "web.js",
  "js",
  "web.jsx",
  "jsx",
  "json",
  "node",
  "mjs"
],
"globals": {
  "ts-jest": {
    "tsConfigFile": "tsconfig.test.json"
  }
}

这是我正在使用的依赖项:

"typescript": "^2.9.2",
"puppeteer": "^1.1.1",
"jest-image-snapshot": "^2.3.0",
"jest": "22.4.2",
"jest-puppeteer-preset": "^2.0.1",
"ts-jest": "22.0.1",

如有任何帮助,我们将不胜感激!


解决方案: 结合下面的标记答案和 this guide 对我来说一切顺利。出于某种原因,我试图将 browser 作为全局变量访问。原来我从一开始就做错了。您应该这样定义浏览器:

  const browser = await puppeteer.launch({
    headless: true // whether you want to run the test headless
  });

最终成功了。

browser not defined for ts-jest and puppeteer

您需要确保安装了 @types/jest-environment-puppeteer,因为它提供了全局 browser 定义。

更多