1

如何在使用 Chai 作为断言库时断言来自异步函数的值

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
              })
            })
        })
    }
})

这可以通过 chai request.Response 来实现。然后但不解决

4

1 回答 1

1

您肯定会从 postProject .then 函数返回 res 但不存储它,然后解决 promise 但实际上并未使用 res 解决。

这就是为什么在测试用例中未定义结果。因此,将 res 存储在 temp 中并从 promise 中 resolve(temp)

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
    })
}

注意:如果响应像你说的那样来,这一切都有效

于 2020-09-04T23:23:39.383 回答