When using Jest and Playwright, I encountered an issue where I wanted to launch the browser from setupFilesAfterEnv
in order to avoid repeating the process in every test file. Despite successfully launching the browser and having global variables accessible for testing purposes, I kept receiving an error message: 'TypeError: global.browser.newContext is not a function'. My setup involves using Babel to incorporate TypeScript into Jest.
My Configuration
jest.config.cjs
const config = {
testTimeout: 20000,
setupFilesAfterEnv: ["<rootDir>/setup.ts"]
};
module.exports = config;
setup.ts
import {chromium} from "playwright-chromium";
global.browser = chromium.launch({headless: false});
global.my_val = "10";
test.test.ts
describe("Test", () => {
let context;
let page;
beforeEach(async () => {
console.log("Global 10")
console.log(global.my_val)
context = await global.browser.newContext();
page = await context.newPage();
})
test(...)
The browser launches properly, as confirmed by its presence in the list of processes (although it runs in headless mode despite being set to false).
console.log(global.my_val)
correctly displays 10, indicating that global variables from the setup are visible within this context.
However, the following error is hindering my progress:
TypeError: Cannot read properties of undefined (reading 'newContext')
28 |
29 | beforeEach(async () => {
> 30 | context = await global.browser.newContext();
| ^
31 | page = await context.newPage();
32 | })
33 |