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
The solution suggested by Meni Roytenburd is correct. If you don't like the fact that every function needs to be exposed to the browser separately, the only idea that comes to mind is transpiling your project to a single JavaScript file first and then injecting it as a tag — just like you would in real life.
The first step would be to generate a single JavaScript file with your bundle. Sometimes this can be accomplished with the TypeScript compiler alone, but a tool like Webpack can be used, too.
Once it's done, you can move your bundle to the client from within Puppeteer:
await page.addScriptTag({ path: 'path/to/the/bundle' });
Keep in mind this still may expose your functions to the global scope, hence accessing them via window
.
let size = await page.evaluate(() => {
const canvas = window.createHdpiCanvas();
return [canvas.width, canvas.height];
});
console.log(size); // [ 300, 150 ]
Another downside to this approach to having to deal with the warnings generated by TypeScript — at this point it doesn't know that createHdpiCanvas
exists on window
, so accessing window.createHdpiCanvas
will cause an error.