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

287 views Asked by At

I am getting an error when I am using Nock twice in my unit tests. It seems like I am using Nock incorrectly. The first test passes but the second one has an error:

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

Below is the unit test and the code I want to do the unit test for. I am using mocha, nock and axios library.

test-users.js

const chai = require('chai');
const expect = chai.expect;
const nock = require('nock');
const assert = require('assert');
const axios = require('axios');
axios.defaults.adapter = require('axios/lib/adapters/http');
const users = require('../services/users');

describe('Tests users', function () {

  afterEach(function () {
    nock.cleanAll();
  });

  it('verifies successful response', async () => {
    const scope = nock('https://sample.com').post('/users').reply(200, {});
    const result = await users.saveData('Smith', 'John')
    expect(result).to.be.an('object');
    scope.done();
  });

  it('verifies unsuccessful response', async () => {
    const scope = nock('https://sample.com').post('/users').reply(400, {});
    const result = await users.saveData('Smith', 'John');
    expect(result).to.be.an('object');
    scope.done();
  });
});

This is my users.js.

const axios = require('axios')
const FormData = require('form-data');
const data = new FormData();

exports.saveData = async (lastName, firstName) => {
  try {
    data.append('lastName', lastName);
    data.append('firstName', firstName);
  } catch (error) {
    throw Error(error);
  }
  const url = 'https://sample.com/users';

  const config = {
    method: 'post',
    url,
    data: data
  };
  try {
    const result = await axios(config);
    return result;
  } catch (error) {
    throw new Error('An Error Occurred');
  }
}
0

There are 0 answers