Hugo
Hugo

Reputation: 11

How to pass a variable from a Jest beforeAll to a Jest describe through an exported function

I want to pass variable 'page' to Jest's description function:

describe('Filter Test', () => {

        beforeAll(async () => {
            jest.setTimeout(20000);
            browser = await puppeteer.launch()
            page = await browser.newPage();
            await page.goto(url, {waitUntil: 'networkidle2'});
            await page.setViewport({width: 1828, height: 994});

        })
    description.authenticate(page);
}

This function looks something like this:

const authenticate = (page) => {


        describe('describe 1', () => {
            test('blabla 1', async () => snap.screenshotPageCompare(page,'login-page.png'));
            test('blabla 2', async () => auth.login(page));

        });
    };

exports.authenticate = authenticate;

The displayed code is not working, 'page' appears as undefined

Upvotes: 1

Views: 2455

Answers (1)

Malvineous
Malvineous

Reputation: 27340

This is one of the drawbacks with Jest. You can do it with other testing frameworks like Mocha, but not with Jest.

The reason is that the describe() and test() functions don't actually run the code you pass in, they just store those functions to be run later.

This means in your case, your description.authenticate() function is called before any tests ran, and indeed before the beforeAll() code has run, which is why you are getting the undefined value.

The only way you can do it is by taking the code out of beforeAll() and putting it first inside the describe() block. This way it will run while the tests are being created, but the drawback is that if there's an error (like your browser setup fails) you'll get a generic failure with no detail to hint at what went wrong.

Here's another example of the ordering:

// Code here runs first (1)

describe('Test group', () => {

  // Code here runs third (3)

  beforeAll(() => {
    // Code here runs sixth (6)
  });

  // Code here runs fourth (4)

  test('Test case', () => {
    // Code here runs seventh (7)
  });

  // Code here runs fifth (5)

});

// Code here runs second (2)

If you try to match your code up against this structure, you will see that the test cases you are creating inside description.authenticate() will happen in step 4, but you are trying to use variables that do not have their value set until step 6.

But you can also see that if you move your code anywhere before step 4, then it will work.

Upvotes: 4

Related Questions