Search code examples
typescriptmocha.jschaichai-http

Not able to use done() or async/await to fix my promise not resolving


I'm trying to learn api testing with chai-http and mocha. I have tried done() and async/await but I cannot understand why it has not fixed the following issue -

Bug -

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

Spec File -

import * as chai from 'chai';
import { assert } from 'chai';
import chaiHttp = require('chai-http');
import 'mocha';

chai.use(chaiHttp);
const expect = chai.expect;
const url = 'https://api.weather.gov';

describe('Weather API', () => {

    it('Should be up and running', () => {
        return chai.request(url).get('/').then(res => {
            expect(res).to.be.status(200);
        });
    });

    it('Should return weather of washington monument', () => {
        return chai.request(url).get('/gridpoints/LWX/96,70/forecast')
            .set('User-Agent', '[email protected]')
            .set('Accept', 'application/vnd.noaa.dwml+xml')
            .then(res => {
                expect(res).to.be.status(200);
                console.log(res.body.properties.periods);
            });
    });
});

Otherwise, I did not implement the solutions I tried, correctly. Any help is most appreciated.


Solution

  • When you work with promises you have to use chai-as-promised and, with this, you can do using async/await in this way:

    import chaiAsPromised = require("chai-as-promised");
    chai.use(chaiAsPromised);
    
    //...
    
    it('Should be up and running', async () => {
        var response = await chai.request(url).get('/')
        return response.should.have.status(200)
        // you can use "return expect(response).to.have.status(200);" too
      })
    

    Note that now done is not used and is added a return.