Marek Dědič
Marek Dědič

Reputation: 89

How to mock browser globals in playwright?

I'm looking for a way to mock a global variable in playwright tests.

I tried running

page.evaluate(() => {
  window.myVar = jest.fn();
});

however, I get page.evaluate: ReferenceError: jest is not defined - which makes sense since the evaluation is running in the browser and jest is in the runner...

Is there a way to mock things in the browser?

(for context, why I want to do this - I am creating a google apps script app which always has the google api available at runtime, so I need to mock that in my tests...)

Upvotes: 2

Views: 4085

Answers (1)

hardkoded
hardkoded

Reputation: 21695

You can use exposeFunction to run code on your side:

await page.exposeFunction('myMock', () => console.log('This function runs on the node side'));
await page.evaluate(() => {
  window.myVar = myMock();
});

Upvotes: 1

Related Questions