0

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

1
  • hello @user1660325 have you resolved it? Commented Nov 2, 2019 at 5:53

1 Answer 1

1

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()}`);
  });
});
Sign up to request clarification or add additional context in comments.

14 Comments

Tran Nope its not working with chained async calls and i am getting Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called;
Have you try all of these above ways? If yes, you can follow this pattern. it('should not timeout', (done) => { }).timeout(60000);
Your async function is exceed 2000ms, so it throw a error. So extend timeout by set .timeout(60000) in each test case.
yes @Hay Tran , gave 60000 but then this code is giving same timeout error, common.mocha.before((done) => { // Wait for the server to start up setTimeout(() => { done(); }, 2000); });
So try to increase to 600000
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.