14

Say the script has navigated to a certain page. How to execute a js function inside that script?

describe("TestSuite", () => {
  test("Login", async() => {
    await page.goto(APP);
    await page.waitForSelector("[name=loginForm]");
    await page.click("input[name=username]");
    await page.type("input[name=username]", user.username);
    await page.click("input[name=pwd]");
    await page.type("input[name=pwd]", user.pwd);
    await page.click("input[name=login]");
    await page.waitForSelector(".PageBodyVertical");

 // execute a js function x() here which is loaded with the page.

  }, 60000);
dina
  • 937
  • 1
  • 12
  • 29

2 Answers2

20

Use the .evaluate() function.

describe("TestSuite", () => {
  test("Login", async() => {
    await page.goto(APP);
    await page.waitForSelector("[name=loginForm]");
    await page.click("input[name=username]");
    await page.type("input[name=username]", user.username);
    await page.click("input[name=pwd]");
    await page.type("input[name=pwd]", user.pwd);
    await page.click("input[name=login]");
    await page.waitForSelector(".PageBodyVertical");

    await page.evaluate( function(){
      x();
    } );

  }, 60000);
Pjotr Raskolnikov
  • 1,558
  • 2
  • 15
  • 27
2

Example with args:

let a1 = "hello";
let a2 = " world";

const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.evaluate(function(a1, a2){
      console.log('msg: ' + a1 + a2); // This code runs in the page's context and returns the result
}, a1, a2);

Puppeteer evaluate docs: https://pptr.dev/api/puppeteer.page.evaluate

Note 1: In order to see the console print you need to add a listener
Note 2: In order to invoke your own functions within evaluate you need to expose the function

Mercury
  • 7,430
  • 3
  • 42
  • 54