【问题标题】:Call Asynchronous functions with Chai request使用 Chai 请求调用异步函数
【发布时间】:2020-08-20 13:48:32
【问题描述】:

使用 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 来实现。然后但不解决

【问题讨论】:

    标签: javascript mocha.js chai asynchronous-javascript


    【解决方案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
        })
    }
    

    注意:如果响应如您所说,这一切都有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 2018-02-18
      相关资源
      最近更新 更多