Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

browser not defined for ts-jest and puppeteer

I am trying to create snapshot-tests with puppeteer for my typescript create react app. Regular testing with jest is working fine, but as soon as I am trying to create the snapshots with the browser and have to use the browser variable within my .test.ts file I'm being told that browser is not defined.

I can't seem to work around this problem even though I have been trying to resolve this issue for hours.

For reference, here are my jest settings within my package.json file:

  "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"
  }
}

And here are the dependencies I'm using:

"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",

Any help would be appreciated a lot!


SOLUTION: In combination with the marked answer below and this guide things worked out for me. For some reason I was trying to access browser as a global variable. Turns out I was doing things wrong from the very beginning. You are supposed to define browser like this:

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

which ended up working.

like image 627
Jonas Bergner Avatar asked Jan 01 '23 21:01

Jonas Bergner


1 Answers

browser not defined for ts-jest and puppeteer

Per the jest puppeteer docs you need to ensure you have @types/jest-environment-puppeteer installed as that provides the global browser definition.

like image 55
basarat Avatar answered Jan 04 '23 09:01

basarat