返回介绍

Using with puppeteer

发布于 2020-04-21 15:39:30 字数 5232 浏览 1115 评论 0 收藏 0

With the Global Setup/Teardown and Async Test Environment APIs, Jest can work smoothly with puppeteer.

Generating code coverage for test files using Puppeteer is currently not possible if your test uses page.$eval, page.$eval or page.evaluate as the passed function is executed outside of Jest's scope. Check out issue #7962 on GitHub for a workaround.

Use jest-puppeteer Preset

Jest Puppeteer provides all required configuration to run your tests using Puppeteer.

  1. First install jest-puppeteer
yarn add --dev jest-puppeteer
  1. Specify preset in your Jest configuration:
{
  "preset": "jest-puppeteer"
}
  1. Write your test
describe('Google', () => {
  beforeAll(async () => {
    await page.goto('https://google.com');
  });

  it('should be titled "Google"', async () => {
    await expect(page.title()).resolves.toMatch('Google');
  });
});

There's no need to load any dependencies. Puppeteer's page and browser classes will automatically be exposed

See documentation.

Custom example without jest-puppeteer preset

You can also hook up puppeteer from scratch. The basic idea is to:

  1. launch & file the websocket endpoint of puppeteer with Global Setup
  2. connect to puppeteer from each Test Environment
  3. close puppeteer with Global Teardown

Here's an example of the GlobalSetup script

// setup.js
const puppeteer = require('puppeteer');
const mkdirp = require('mkdirp');
const path = require('path');
const fs = require('fs');
const os = require('os');

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');

module.exports = async function () {
  const browser = await puppeteer.launch();
  // store the browser instance so we can teardown it later
  // this global is only available in the teardown but not in TestEnvironments
  global.__BROWSER_GLOBAL__ = browser;

  // use the file system to expose the wsEndpoint for TestEnvironments
  mkdirp.sync(DIR);
  fs.writeFileSync(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
};

Then we need a custom Test Environment for puppeteer

// puppeteer_environment.js
const NodeEnvironment = require('jest-environment-node');
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const os = require('os');

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');

class PuppeteerEnvironment extends NodeEnvironment {
  constructor(config) {
    super(config);
  }

  async setup() {
    await super.setup();
    // get the wsEndpoint
    const wsEndpoint = fs.readFileSync(path.join(DIR, 'wsEndpoint'), 'utf8');
    if (!wsEndpoint) {
      throw new Error('wsEndpoint not found');
    }

    // connect to puppeteer
    this.global.__BROWSER__ = await puppeteer.connect({
      browserWSEndpoint: wsEndpoint,
    });
  }

  async teardown() {
    await super.teardown();
  }

  runScript(script) {
    return super.runScript(script);
  }
}

module.exports = PuppeteerEnvironment;

Finally we can close the puppeteer instance and clean-up the file

// teardown.js
const os = require('os');
const rimraf = require('rimraf');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
module.exports = async function () {
  // close the browser instance
  await global.__BROWSER_GLOBAL__.close();

  // clean-up the wsEndpoint file
  rimraf.sync(DIR);
};

With all the things set up, we can now write our tests like this:

// test.js
const timeout = 5000;

describe(
  '/ (Home Page)',
  () => {
    let page;
    beforeAll(async () => {
      page = await global.__BROWSER__.newPage();
      await page.goto('https://google.com');
    }, timeout);

    it('should load without error', async () => {
      const text = await page.evaluate(() => document.body.textContent);
      expect(text).toContain('google');
    });
  },
  timeout,
);

Finally, set jest.config.js to read from these files. (The jest-puppeteer preset does something like this under the hood.)

module.exports = {
  globalSetup: './setup.js',
  globalTeardown: './teardown.js',
  testEnvironment: './puppeteer_environment.js',
};

Here's the code of full working example.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文