未为ts-jest和puppeteer定义浏览器

Jon*_*ner 3 typescript jestjs puppeteer

我正在尝试使用puppeteer为我的打字稿create react app创建快照测试。使用jest进行常规测试可以很好地工作,但是当我试图用浏览器创建快照并必须在我的文件中使用变量时,我被告知。browser.test.tsbrowser 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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

"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",
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!


解决方案:结合以下标记的答案和本指南,一切对我而言都是可行的。由于某种原因,我试图browser作为全局变量进行访问。原来,我从一开始就做错了。您应该这样定义浏览器:

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

最终工作了。