N
N
Nikita Sokolov2020-07-26 12:00:50
Unit testing
Nikita Sokolov, 2020-07-26 12:00:50

How to get element from page in puppeteer?

I have this code:

import puppeteer from 'puppeteer';
import $ from 'jquery';

let page, browser, input;

const contentHtml = `<html><body><input id='test' type='text'></body></html>`;

beforeAll(async () => {
  browser = await puppeteer.launch();
  page = await browser.newPage();
  await page.setContent(contentHtml);
  await page.evaluate(() => {
    input = page.$('input#test');
    console.log(input);
  });
});

describe('View', () => {
  test('Input is defined', async () => {
    expect(input).toBeDefined();
  });
});

afterAll(() => {
  browser.close();
});

I'm trying to form a page from a string... I don't know if this is possible at all? What to fix here to get this input? On console.log it swears like this:
<br>
Evaluation failed: ReferenceError: page is not defined<br>
<br>
      at __puppeteer_evaluation_script__:2:5<br>
      at ExecutionContext._evaluateInternal (node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:217:19)<br>
      at ExecutionContext.evaluate (node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:106:16)<br>
      at Object. (src/plugin/tests/view.test.ts:12:3)<br>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
d-sem, 2020-07-26
@wb_by

What happens inside page.evaluate is the equivalent of the browser console on the page.
Accordingly, in this there is not a page object, nor $.
To get this input, you need to use standard JS tools and return a value from promises.

const puppeteer = require('puppeteer');
const contentHtml = `<html><body><input id='test' type='text'></body></html>`;

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setContent(contentHtml);
    const type = await page.evaluate(() => {
        return document.getElementById('test').type;
    }).catch(e => console.dir(e));
    console.dir(type);
    await browser.close();
})();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question