【问题标题】:browser not defined for ts-jest and puppeteer没有为 ts-jest 和 puppeteer 定义浏览器
【发布时间】:2018-09-10 18:12:24
【问题描述】:

我正在尝试使用 puppeteer 为我的typescript create react app 创建 snapshot-tests。使用 jest 进行常规测试工作正常,但是一旦我尝试使用 浏览器 创建快照并且必须在我的 .test.ts 中使用 browser 变量文件告诉我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
  });

最终成功了。

【问题讨论】:

    标签: typescript jestjs puppeteer


    【解决方案1】:

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

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

    更多

    【讨论】:

    • 感谢您的回复。这实际上解决了“浏览器”在我的编辑器中被标记为未定义的问题。但是,在运行测试时,我仍然遇到浏览器未定义的相同错误。
    • 好的,我得到了它的工作并编辑了我的问题以包含解决方案:)
    • 感谢您提供文档链接。我完全错过了这一点,并且在这上面浪费了太多时间。看起来你需要@types/puppeteer@types/jest-environment-puppeteer@types/expect-puppeteer
    猜你喜欢
    • 2019-12-29
    • 1970-01-01
    • 2021-03-11
    • 2020-08-20
    • 1970-01-01
    • 2020-01-09
    • 2021-04-23
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多