0

I'm trying to make unit and e2e test on a project, i decided to use jest and puppeteer (with also jest-puppeteer) to achive this.

My problem is that I initialize a var, named tools, in an script of index.html and i want to get it to do some test after, but he return me an error that is "tools" is not defined.

I already tryed to see on the web if a solution exist but without success.

Can I have somme help ? :')

Code extracts:

// index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>

        <script src="./js/Variables.js"></script>
        <script src="./js/Tools.js"></script>
    </head>

    <body>
        <script>
            tools = new Tools();
        </script>
    </body>
</html>
// Variables.js
let tools;
// Tools.js
class Tools {
    constructor(){
        // do some stuff
    }

    test(){
        return "test string";
    }
}
// app.test.js
beforeAll(async () => {
    await page.goto('http://myPage/');
});

test("can i get \"tools\"", () => {
    console.log(tools); // tools is not defined
    expect(tools.test()).toBe("test string");
});

EDIT 22/07/2022 15:38

I finally managed to get something BUT now i can't use functions on it, the error says that tools.test() is not a function, it seems to retrieve only his "pure" value and not the Tools instance.

test("can i get \"tools\"", async () => {
    let tools = await page.evaluate('tools');
    console.log(tools); // gets {} (doesn't seems to retrieve instance)
    expect(tools.test()).toBe("test string"); // TypeError: tools.test() is not a function
});
aynber
  • 22,380
  • 8
  • 50
  • 63
  • I'm confused as to whether your goal is to call tools in node or the browser. If you want to use them in Node, simply `require`/`import` them as you would in any other Node script. If you want tools to run in the browser, then there are [many ways](https://stackoverflow.com/questions/72156753/how-do-i-expose-an-object-with-a-bunch-of-functional-definitions-or-methods-to/72157472#72157472) such as `page.addScriptTag` or simply including the script in your index and serving it up statically as you're doing. Possible [xy problem](https://meta.stackexchange.com/questions/66377/) here. – ggorlen Jul 22 '22 at 14:11
  • My goal is to get `tools` instance from the script markup in the DOM because i don't use `import`/`require` and `exports` (and i prefer to don't use them cause of my project requirement) – Louis Lemasson Jul 25 '22 at 09:24

1 Answers1

0

I can use class method by using

let toolsTest = await page.evaluate(() => tools.test());

BUT it's not really what i want... I really want to get an instance to test some sh!t on it.

However let tools = await page.evaluate(() => tools); still doesn't give me the instance, there is really no way to achive this ?

So i really need to know how to get variables in script tag to use them with jest. Maybe another test library can do the job such as mocha ?