Search code examples
seleniumprotractortimeoutmocha.jsassert

How to avoid timeout for mocha asynchronous tests


I have a mocha test that I am trying to run but it keeps on giving me the following error

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called

it('should login into account', (done) => {
        let user_login = require("../../data/login.json");
        mongoManager.insertDocuments("user", user_login.content, () => {
            loginPage.setUserName('demodgsdg');
            loginPage.setPassword('123');
            loginPage.submit();
            browser.waitForAngularEnabled(true);
            Assert.equal(element(by.id('navbar')).isDisplayed(), true, "login page is not loaded");
            setTimeout(done(), 50000);
            done();
        });

    });

Whats the best way to run an asynchronous test in mocha so that it doesnt exceed its alotted time? Or should I set the timeout on the test function


Solution

  • You need to do it this way

    it('should login into account', function (done) {
            this.timeout(50000);
    
            let user_login = require("../../data/login.json");
            mongoManager.insertDocuments("user", user_login.content, () => {
                loginPage.setUserName('demodgsdg');
                loginPage.setPassword('123');
                loginPage.submit();
                browser.waitForAngularEnabled(true);
                Assert.equal(element(by.id('navbar')).isDisplayed(), true, "login page is not loaded");
                setTimeout(done(), 50000);
                done();
            });
    });
    

    If you read https://mochajs.org/#timeouts

    Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context. For example, the following code will fail due to the nature of lambdas:

    describe('my suite', () => {
      it('my test', () => {
        // should set the timeout of this test to 1000 ms; instead will fail
        this.timeout(1000);
        assert.ok(true);
      });
    });
    

    If you do not need to use Mocha’s context, lambdas should work. However, the result will be more difficult to refactor if the need eventually arises.