简体   繁体   中英

Async await Node.js Unit Testing code using Chai and mocha

I'm quite new to node and express. And have been trying to write test code using mocha, chai. Here's the part of the source code.

googleService.js:

const axios = require('./axios');

exports.hitGoogle = async (requestUrl, payload) => {
  let response = {};
  await axios.post(`${requestUrl}`, payload)
    .then((resp) => {
      response = resp;
      console.log(response);
    })
    .catch((err) => {
      console.error(err);
    });
  return response;
};

readGoogle.js

const googleService = require('./googleService');

exports.execute = async (data) => {
  console.log(`data ${JSON.stringify(data)}`);
  console.log(`Name ${data.name}`);
  console.log(`Salary ${data.salary}`);
  console.log(`Age ${data.age}`);
  const payload = { name: data.name, salary: data.salary, age: data.age };

  await googleService.hitGoogle('http://dummy.restapiexample.com/api/v1/create', payload)
    .then((response) => {
      if (response.status === 200 || response.status === 201) {
        console.log(response.status);
        return true;
      }
      return false;
    })
    .catch((err) => {
      console.log(err);
    });
  return true;
};

And here is my unit test file:

const readGoogle = require('./readGoogle');

const jmsPayload = { age: '23', name: 'test', salary: '123' };

describe('Google ', () => {
  it('POST: Google.', async () => {
     readGoogle.execute(jmsPayload).then((result) => {
     results = result;
    console.log(`Final Result : ${results.toString()}`);
  });
});

When I execute this test file, post is successful,

hitGoogle url=http://dummy.restapiexample.com/api/v1/create
hitGoogle payload=[object Object]
{ status: 200,
  statusText: 'OK',

Input values passed from test class to readGoogle.js is also read inside that,

data {"age":"23","name":"test","salary":"123"}
Name test
Salary 123
Age 23

**But I am getting Promise as output.** 

**SO I have rendered the promised value to a normal string and getting 'true' as final output.**

Also,

  • 1)Is this is the right way of testing the async-await module?

    2) Do we need to add anything else in this test code like Settimeout or beforeEach or afterEach blocks?

    3) Do we need to use Sinon for spying or adding a stub to 'payload' in googleService.js?

Can anyone help or suggest me the right path?

Tried async way for executing test cases one by one in order as below,

const readGoogle = require('./readGoogle');

const jmsPayload = { age: '23', name: 'test', salary: '123' };

const common = require('./common');
const chaiHttp = common.chaiHttp;
common.chai.use(chaiHttp);

describe('Google ', () => {
  common.mocha.before((done) => {
    // Wait for the server to start up
    setTimeout(() => {
      done();
    }, 1000);
  });

  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
    setTimeout(() => {
    }, 1000);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
});

But then I am getting,

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

Thanks in advance

You can use the 2 following solutions:

1) Callback convention:

describe('Google ', () => {
    it('POST: Google.', (done) => {
        readGoogle.execute(jmsPayload).then((result) => {
            results = result;
            console.log(`Final Result : ${results.toString()}`);
            done();
        }).catch((e) => {
            done();
        });
    });
});

2) async/await convention

describe('Google ', () => {
  it('POST: Google.', async () => {
    const results = await readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${results.toString()}`);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM