Friday 7 April 2017

In node, how do you wait until a callback has been called?

I have a function which resolves by taking a callback like function(error, result) { ... } as a parameter. I'm trying to use mocha to test this function, but the problem is that the function returns asynchronously, so there's no good place for me to put the done(). If I put inside my result handler, it takes too long and mocha times out. If I put it outside, the test always passes because the handler hasn't been called yet. Here is my code. What's the best way to get around this?

lbl.createLabels is a function that takes an array of customers, and a directory, and creates a bunch of files in that directory, and then asynchronously calls the callback of type: function(error, callback).

describe('Tests', () => {
    it('returns a list of customer objects', (done) => {
        lbl.createLabels(customers, __dirname + "/..", (err, result) => {
            err.should.equal(undefined)
            result.should.be.a('array')
            result[0].should.have.property('id')
            result[0].should.have.property('tracking')
            result[0].should.have.property('pdfPath')
            const a = {prop:3}
            a.prop.should.be.an('array')
            done() // putting done() here results in a timeout
        })
        done() putting done here results in the test succeeding all the time and exiting before the callback gets called
    })
})



via user3685285

No comments:

Post a Comment