Pavel Smirnov
Pavel Smirnov

Reputation: 33

Why am I keep getting Error: Timeout of 2000ms exceeded from Mocha on async?

I am trying to start javascript testing on Selenium, but I am stucked at the start.

MochaJS never waits for the end of test, instead throwing after 2 seconds

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

My code is

const {Builder, By, Key, until} = require('selenium-webdriver');
let assert = require('chai').assert;

describe('Test Suite', function() {
    it('should do', async function(done) {
        try {
        let driver = new Builder().forBrowser('firefox').build();
        await driver.get('http://www.google.com/ncr');
        const title = await driver.getTitle();
        assert.equal(title, 'Google');
        } catch(err) {
            console.log(err);
        } finally {
            await driver.quit();
        }
        done();
    })
})

Mocha says that I have unresolved promises in my code, but are there such?

Upvotes: 2

Views: 4253

Answers (1)

Pavel Smirnov
Pavel Smirnov

Reputation: 33

Okay, after investigating I will try to answer my own question as I solved it.

Firstly, the Error: Timeout of 2000ms exceeded. is a common issue and it is just that - timeout was exceeded, but tests didn't run (cause they need more time to run). It is documented on stackoverflow pretty good.

The next problem is that Mocha awaits promise or done function to finish the test. When I wrote

it('should do', async function(done) {
    try {
    let driver = new Builder().forBrowser('firefox').build();
    await driver.get('http://www.google.com/ncr');
    const title = await driver.getTitle();
    assert.equal(title, 'Google');
    } catch(err) {
        console.log(err);
    } finally {
        await driver.quit();
    }
    done();
})

It neither got the promise nor it got done, cause it does not work with async/await mechanism, only with standard promises.

So I removed done and also removed try-catch block completely, now it works at last!

The final code is

describe('Test Suite', function() {
    this.timeout(0);

    before(async function() {
        this.driver = await new Builder().forBrowser('firefox').build();
    });

    it('should do', async function() {
        await this.driver.get('http://www.google.com/ncr');
        const title = await this.driver.getTitle();
        assert.equal(title, 'Google1121312213');
    })

    after(async function() {
        this.driver.quit();
    })
});

Upvotes: 1

Related Questions