Required plug-ins and what they do

  • jest
npm i jest
Copy the code
  • puppeteer
npm i puppeteer
Copy the code
  • jest-puppeteer
npm i jest-puppeteer
Copy the code

Jest-puppeteer exposes the global variables browser, Page, context. Developers can use pages directly without having to create a page with const page = browser.newPage().

  • expect-puppeteer
npm i expect-puppeteer
Copy the code

Expect – Puppeteer Performs secondary encapsulation based on the puppeteer API, simplifying operations.

Jest.config.js configuration file

module.exports = {
  preset: 'jest-puppeteer'.moduleNameMapper: {
    '^ @ / (. *) $': '<rootDir>/src/$1'
  },
  rootDir: '. '.testMatch: [
    "**/__tests__/**/*.[jt]s? (x)"."* * /? (*) +(spec|test).[tj]s? (x)"].transform: {
    "\\.js$": 'babel-jest'
  },
  transformIgnorePatterns: [
    "/node_modules/",].setupFilesAfterEnv: ["expect-puppeteer"]};Copy the code

Jest -puppeteer.config.js configuration file

module.exports = {
  launch: {
    headless: false,},browser: "chrome".browserContext: "default"};Copy the code

Test case writing

describe('Puppeteer Primer'.() = > {
  test('hello world'.async() = > {await page.goto("https://getbootstrap.com/docs/4.3/components/forms/#checkboxes-and-radios");
    const checkboxStatus = await page.$eval('#defaultCheck1'.(checkbox) = > checkbox.checked);
    expect(checkboxStatus).toBeFalsy();
  });

  test("Select multiple controls".async() = > {await page.goto("https://getbootstrap.com/docs/4.3/components/forms/#checkboxes-and-radios");
    const radios = await page.$$eval('input[name=exampleRadios]'.(elems) = > elems.map(elem= > elem.value));
    expect(radios.length).toBeGreaterThan(1);
  });
});
Copy the code

Demo code

Reference code