Zag Gol
Zag Gol

Reputation: 1076

Puppeteer - failed to pass variable into an evaluate function

I have a mission to change the background code of or existing Mocha tests to run with Puppeteer. here is the test, that should not be changed:

return assertOnLeft(function (asserter) {
            asserter(window.location.href.indexOf("http://XXXX:3000/regression_test_pages/links_page1.html") == 0,
             "Address should be links_page.html");
});

I tried to implement assertOnLeft function:

const assertOnLeft = async (predicate) => {
    const assert = require("assert");

    const asserterOk = assert.ok;
    await page.evaluate((asserterOk, predicate) => {
        return predicate(asserterOk)
    }, asserterOk, predicate)
    .catch((e) => console.log("error", e));
}

But I get a error:

error Error: Evaluation failed: TypeError: predicate is not a function
at __puppeteer_evaluation_script__:2:16
at ExecutionContext._evaluateInternal (/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:218:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async ExecutionContext.evaluate (/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:107:16)
at async assertOnLeft (/var/tmp/regression_tests/puppeteer/testWrapper.js:143:5)

Upvotes: 1

Views: 154

Answers (1)

Massimo Rebuglio
Massimo Rebuglio

Reputation: 341

page.evaluate serialize a function and send it to the puppeeter browser. The code inside page.evaluate isn't a part of you code, and you can't call a function of your code from it.

If you want a "tricky" solution you cant try exposeFunction... but usually is not a good way. If you post the predicted code i can suggest you a better way

Try this:

const assert = require("assert");

const asserterOk = assert.ok;

await page.exposeFunction("predicted", predicted);

await page.evaluate((asserterOk, predicate) => {
    return predicted(asserterOk, predicate)
}, asserterOk, predicate)
    .catch((e) => console.log("error", e));

Upvotes: 2

Related Questions