1

How to assert the values from asynchronous function while using Chai as assertion library

const testData = ['PTesting', 'P2', 'P3']
describe("End to end testing.", function () {
    before(function () {
        logger.info('End to end test cases started');
    });
    after(function () {
        logger.info('End to end test cases completed')
    });
    if (testData[0] == 'PTesting') {
        describe('API', ()=> {
            this.timeout(5000); // How long to wait for a response (ms)
            before(function () {
                logger.info(' Test cases started');
            });
            after(function () {
                logger.info(' Test cases completed');
            });
            async function postProject(){
                return new Promise(resolve =>{
                  chai.request(requestURL)
                  .post('projects')
                   .auth(Username,Password)
                  .send({
                      'customerName': 'Testing123',
                   })
                  .then(function (res) {
                      var projectCode = res.body.code
                    // var projectCode='P80'
                      console.log('project created successfully'+projectCode)
                      return res
                  })
                  resolve();// How to resolve here
            })
        }
            it('Testing for async projects', async () => {
              return postProject().then(result => {
                expect(result).to.have.status(200); //result is coming as undefined
              })
            })
        })
    }
})

Can this be achieved with chai request.Response is coming in .then but not into resolve

BTVS
  • 21
  • 4

1 Answers1

1

You are for sure returning res from postProject .then function but not storing it and then resolving the promise but not actually resolving with res.

That is why result is undefined in test case. So, store res in temp and resolve(temp) from promise

async function postProject(){
    return new Promise(resolve =>{
        let temp = chai.request(requestURL)
              .post('projects')
              .auth(Username,Password)
              .send({
                  'customerName': 'Testing123',
               })
              .then(function (res) {
                  var projectCode = res.body.code
                // var projectCode='P80'
                  console.log('project created successfully'+projectCode)
                  return res
              })
         return resolve(temp); //use return if don't want to execute further
    })
}

Note: this all works if response is coming like you said