PuppeteerEnvironment.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const { readFile } = require('fs').promises;
  2. const os = require('os');
  3. const path = require('path');
  4. const puppeteer = require('puppeteer');
  5. const NodeEnvironment = require('jest-environment-node');
  6. const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
  7. /**
  8. * Custom Puppeteer environment as documented on https://jestjs.io/docs/puppeteer.
  9. * We don’t use jest-puppeteer because it’s unreliable.
  10. */
  11. class PuppeteerEnvironment extends NodeEnvironment {
  12. async setup() {
  13. await super.setup();
  14. // get the wsEndpoint
  15. const wsEndpoint = await readFile(path.join(DIR, 'wsEndpoint'), 'utf8');
  16. if (!wsEndpoint) {
  17. throw new Error('wsEndpoint not found');
  18. }
  19. this.global.TEST_ORIGIN =
  20. process.env.TEST_ORIGIN ?? 'http://localhost:8000';
  21. // connect to puppeteer
  22. this.global.browser = await puppeteer.connect({
  23. browserWSEndpoint: wsEndpoint,
  24. defaultViewport: {
  25. width: 1024,
  26. height: 768,
  27. },
  28. });
  29. this.global.page = await this.global.browser.newPage();
  30. }
  31. async teardown() {
  32. await this.global.page.close();
  33. await super.teardown();
  34. }
  35. getVmContext() {
  36. return super.getVmContext();
  37. }
  38. }
  39. module.exports = PuppeteerEnvironment;