user3685285
user3685285

Reputation: 6586

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 exiting before the callback gets called
    })
})

Upvotes: 1

Views: 2170

Answers (1)

Dai
Dai

Reputation: 155280

Mocha's documentation has an entire section describing how to test asynchronous code:

https://mochajs.org/#asynchronous-code

Testing asynchronous code with Mocha could not be simpler! Simply invoke the callback when your test is complete. By adding a callback (usually named done) to it(), Mocha will know that it should wait for this function to be called to complete the test.

describe('User', function() {
    describe('#save()', function() {
        it('should save without error', function(done) {
            var user = new User('Luna');
            user.save(function(err) {
                if (err) done(err);
                else done();
            });
        });
    });
});

Upvotes: 1

Related Questions