从Puppeteer浏览器/页面上下文中提取本机界面

时间:2018-12-29 23:30:34

标签: javascript jestjs puppeteer

是否可以从Browser或Page实例检索本机接口,以便检查对象是否为instanceof此接口?

例如,在一个开玩笑的测试上下文中(由于某些原因,CanvasRenderingContext2D不可用,因为它是Node上下文,而不是JSDOM或浏览器API的其他仿真):

it("should create an instance of CanvasRenderingContext2D", async () => {
  expect.assertions(1);

  const context = await page.evaluate(() => {
    return document.createElement("canvas").getContext("2d");
  });

  // Could a JSHandle be used somehow?
  const CanvasRenderingContext2DInterface = await page.evaluateHandle(() => CanvasRenderingContext2D);

  expect(context).toBeInstanceOf(CanvasRenderingContext2DInterface);
});

1 个答案:

答案 0 :(得分:1)

应该直接在Puppeteer浏览器/页面中评估实例检查,否则执行上下文会不同。

it("should create an instance of CanvasRenderingContext2D", async () => {
  expect.assertions(1);

  const isInstanceOfCanvasRenderingContext2D = await page.evaluate(
    () =>
      document.createElement("canvas").getContext("2d") instanceof CanvasRenderingContext2D
  );
  expect(isInstanceOfCanvasRenderingContext2D).toBeTruthy();
});