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

标签 typescript jestjs puppeteer

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

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

作为引用,这里是我的 package.json 文件中的 jest 设置:

  "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

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

关于typescript - 没有为 ts-jest 和 puppeteer 定义浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52263328/

相关文章:

javascript - React Native 问题 : [Unhandled promise rejection: TypeError: f is not a function.(在 'f()' 中, 'f' 未定义)]

javascript - Jest.js 模拟模块中的方法

javascript - 尝试在 enzyme 中设置Props时出现未定义的错误

node.js - waitUntil : 'domcontentloaded' 之后,并非所有 DOM 内容都准备就绪

javascript - Puppeteer page.evaluate querySelectorAll 返回空对象

performance-testing - 使用 Puppeteer/Headless Chrome 报告性能指标

javascript - ES5 定义中的 OmitThisParameter 在 TypeScript 中有什么作用?

javascript - 默认导出的 Typescript 接口(interface)

angular - 错误 TS2688 : Cannot find type definition file for 'angular'

react-native - 为什么 @testing-library/react-native fireEvent 不调用我的 onChange 函数?