Brygom
Brygom

Reputation: 848

Testing with Mocha Chai async function

I have a Hapi JS server with routes, this is my Hapi js Server

const Hapi = require('hapi');

import { Users } from './users';

const port  3000;

const server = new Hapi.Server();

server.connection({ port });

export async function HapiServer() {

  server.route([
    {
      method: 'GET',

      path: '/getUsers',
      config: {
        handler: async (req: any, reply: any) => {
          try {


            await Users.getUsers(req.params.id)
              .then((result) => {
                reply(result);
              });
          } catch (error) {
            reply(error);
          }
        },



      },
    },
  ]);
  await server.start();
  console.log('server running at', server.info.port);
}


HapiServer();

I use Mocha and Chai for make a Unit Testing as follow:

'use strict';
import { should } from 'chai';
import { HapiServer } from '../../server';
const chai = require('chai');
const chaiHttp = require('chai-http');

chai.use(chaiHttp);

describe('testing users ', () => {
    it('can get all users', async (done) => {
        const result = await chai
        .request(HapiServer)
            .get(/getUsers)
        .then((error, response) => {
            if (error) { done(error); }
            response.should.have.status(200);
            done();            
        }).catch(done);
    });
});

When run the test always have this:

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

I already try change my mocha config in package.json

mocha --timeout 10000

What could I be doing wrong? I understand that Mocha supports promises.

Upvotes: 0

Views: 4548

Answers (1)

deerawan
deerawan

Reputation: 8443

we practically combine all the solution (async/await, promise based and callback done) for async test in the test file.

Let's use the recent solution using async/await so it will be:

describe('testing users ', () => {
    it('can get all users', async () => {
        const response = await chai.request(HapiServer).get('/getUsers');
        response.should.have.status(200);          
    });
});

See that in this code there is no done and no then. used.

Hope it helps.

Upvotes: 4

Related Questions