Reputation: 1072
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);
Upvotes: 15
Views: 27271
Reputation: 7988
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
Upvotes: 3
Reputation: 1688
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);
Upvotes: 23