简体   繁体   中英

error with async function in 'before' - testing with mocha and puppeteer

I am trying to launch a chromium browser in the 'before' hook. I keep getting the following error when running the code:

let browser;

describe('Login Tests', function(){

  let page;

  before(async ()=> {

    let launchOptions = {
        headless: false,
        executablePath: '/Applications/Chromium.app/Contents/MacOS/Chromium', 
        args: ['--start-maximized']
    };

    browser = await puppeteer.launch(launchOptions);
    page = await browser.newPage();

    await page.goto('http://localhost:8080');

    await page.waitForSelector('body div');
  })


  it('should bring up login modal when clicking Client Login', async function(){

    await page.waitForSelector('.navbar-start a[href$="#/login"]');

    await page.click('.navbar-start a[href$="#/login"]');

    let url = await page.url()

    assert.equal(url, 'http://localhost:8080/#/login');

  })

//....

})

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

When i pass a callback into the async function and return it when done, I still get the following error. I get the same error in the after hook, too.

Can someone please help me with this, been stuck on this for too long:(

The problem is that mocha has a default timeout of 2000ms per a hook and test. You don't seem to override the default value anywhere.

To override it, you have several options, one is you add this option into .mocharc.json :

{
    "timeout": 20000
}

This will give you a timeout of 20 seconds for "everything" - hooks, tests.

Another option how you can set a different timeout is right inside your describe callback function by calling timeout() method:

describe('...', function () {
    this.timeout(20000);

    before(...);

    it(...);
});

This will again give you a timeout of 20 seconds. This will affect all hooks and tests inside the describe block. If you want to eg set a timeout only for before hook, you type this inside the before hook:

describe('...', function () {    

    before(function () {
        this.timeout(20000);
    });

    it(...);
});

Yet another way of setting up a different timeout could be:

it('...', function () {
   // ...
}).timeout(20000);

which will obviously set a timeout only for this one test.


If I should give a preference, I'd choose the first option because that's where I expect config values to be. Hooks and tests are about test steps, not setting up timeouts, so I'd avoid doing it there. If I need to set a different timeout for one specific test, I'd choose the last option I mentioned for the same reason of readability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM