05 Asynchronous test step with callback - ranhs/soda-test GitHub Wiki

Method with callback

export function addCallback(a: number, b: number, callback:(err:Error, result:number)=>void) {
    setTimeout(() => {
        return callback(null, a+b)
    }, 500)
}

The method above is another method defined in demo.ts file. this method gets 2 numbers and a callback method. The callback method is used to send back the result of the method, or an error if happen (in this example there could not be an error). In this code is emulate async action by waiting 1/2 a second and then calling the callback with the result (no error).
Note that the method addCallback returns imidatly, but he results returns after a while (500ms)

Test-Step with callback

Previously when we wrote a test-step method, when the methods ends the test-step ends. In this case the test-step will ends only after the callback in addCallback will be called. To do this we add to the test-step method a callback argument called done that will be called after the test-step has ended.

import { expect, describe, it, TR, Done } from 'soda-test'
import { addCallback } from './demo'

@it('should test the callback')
addWithCallback(done: Done): TR {

    addCallback(1,2, (err,result) => {
        expect(err).to.not.exist
        expect(result).to.equal(3)
        done()
    })

}

Incase of an error, you can also pass the error to the done method, and get the error information on the test exectuion:

import { expect, describe, it, TR, Done } from 'soda-test'
import { addCallback } from './demo'

@it('should test the callback')
addWithCallback(done: Done): TR {

    addCallback(1,2, (err,result) => {
        if (err) {
            done(err)
        } else {
            expect(result).to.equal(3)
            done()
        }
    })

}

⚠️ **GitHub.com Fallback** ⚠️