0

I have got a function that based on services fetches their time and sums it up. Services need to be fetched from mongoDb database first, so I have written a function that is async

function that fetches time from services

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

Usage:

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

While testing through Postman it fetches all needed data, but I wanted to test this with chakram. In test case, unfortunately, it does not fetches time, which results in empty array in test.

Test case:

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

When testing it logs that getTotalVisitsTime is undefined, while making request via Postman results in integer that describes time. What is wrong with my code?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
janlan
  • 477
  • 1
  • 5
  • 19

1 Answers1

0

const foundServices = await require('../visitType').find({ _id: { $in: services } }).exec(); dont forget .exec();