How to use imported function inside page.evaluate in Puppeteer with Jest?

后端 未结 3 903
走了就别回头了
走了就别回头了 2021-02-20 02:30

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

3条回答
  •  -上瘾入骨i
    2021-02-20 02:53

    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.

提交回复
热议问题