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 try use imported functions inside page.evaluate
.
For example, I have the following in HdpiCanvas.test.ts
:
import { createHdpiCanvas } from "./HdpiCanvas";
test("createHdpiCanvas", async () => {
await page.setViewport({ width: 800, height: 600, deviceScaleFactor: 2 });
let size = await page.evaluate(() => {
const canvas = createHdpiCanvas(); // document.createElement('canvas');
return [canvas.width, canvas.height];
});
console.log(size); // [600, 300] for HDPI canvas and [ 300, 150 ] for a regular one
});
With the commented out document.createElement('canvas')
the test runs just fine and logs [ 300, 150 ]
. But with the createHdpiCanvas()
the following error is thrown by the page.evaluate
function:
Error: Evaluation failed: ReferenceError: HdpiCanvas_1 is not defined
at __puppeteer_evaluation_script__:2:24
The actual createHdpiCanvas
inside HdpiCanvas.ts
is defined as follows:
export function createHdpiCanvas(width = 300, height = 150): HTMLCanvasElement {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
applyHdpiOverrides(canvas);
return canvas;
}
and itself depends on other functions defined in HdpiCanvas.ts
, like applyHdpiOverrides
.