I have a TypeScript project that uses Jest for unit tests and have just added Puppeteer to the mix with the intention to run some tests on the client. It works fine, unless I tr
As you may have figured it out already, the reason why page.evaluate
fails is because the function is evaluated in a different context and the current scope (where createHdpiCanvas
is available outside of the function) is lost.
I’m not familiar with pupeteer at all but by looking at the documentation for that function, there may be something you can try. It’s not pretty but perhaps it’s worth trying:
You could pass createHdpiCanvas
as a parameter, however a function is not serialisable so you would have to do it yourself:
page.evaluate((createHdpiCanvasCode) => {
const createHdpiCanvas = new Function(`return ${createHdpiCanvasCode}`)();
const canvas = createHdpiCanvas();
return [canvas.width, canvas.height];
}, createHdpiCanvas.toString());
However, you would have to inject your dependencies in the same way.