【问题标题】:Asynchronous function works with Postman but not while testing异步功能适用于 Postman,但在测试时不适用
【发布时间】:2022-01-04 00:12:06
【问题描述】:

我有一个基于服务获取时间并总结的功能。服务需要先从mongoDb数据库中取,所以我写了一个函数是async

从服务中获取时间的函数

const getTotalVisitsTime = async (services) => {
    let totalVisitTime = 0
    const foundServices = await require('../visitType').find({ _id: { $in: services } })
    if (foundServices) {
        return new Promise((resolve, reject) => {
            if (foundServices.length === 0) {
                reject('No services for given id(s) found in database')
            } else {
                for (var i = 0; i < foundServices.length; i++) {
                    totalVisitTime += parseInt(foundServices[i].time)
                }
                resolve(totalVisitTime)
            }
        })
    } else {
        throw Error('Problem with querying services occurred. Check id(s)')
    }
}

用法:

module.exports.getAvailableVisitTimesByDate = async (hairdresserId, date, services, salonData) => {
    return getAvailableVisitTimesArray(await getVisitsForGivenDay(hairdresserId, date),
        salonData,
        await getTotalVisitsTime(services).catch(err => { console.log(err) }))
}

通过 Postman 进行测试时,它会获取所有需要的数据,但我想使用 chakram 进行测试。不幸的是,在测试用例中,它没有获取时间,这导致测试中的数组为空。

测试用例:

    it('should return array of available visit times for certain hairdresser, 1 hour-long visit and certain day (10-03-2019)', () => {
        return chakram.get(url, requestBody, { headers: { 'content-type': 'application/json' } })
            .then(response => {
                expect(response).to.have.status(201)
                console.log(response.body)
                //expect(response.body['freeVisitTimes']).to.eql(expectedArrayOfTimes)
            })
    })

在测试时,它会记录 getTotalVisitsTimeundefined,而通过 Postman 发出请求会产生描述时间的整数。我的代码有什么问题?

【问题讨论】:

    标签: node.js express async-await chai chakram


    【解决方案1】:

    const foundServices = await require('../visitType').find({ _id: { $in: services } }).exec(); 不要忘记 .exec();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 2015-09-19
      • 1970-01-01
      • 2014-06-09
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多