06 Asynchronous test step with Promise - ranhs/soda-test GitHub Wiki

Method with Promise

export function addPromise(a: number, b: number): Promise<number> {
    return new Promise<number>( (resolve,reject) => {
        resolve(a+b)
    })
}

The method above is another method defined in demo.ts file. this method gets 2 numbers and returns a promise of a number. The promise is resolved to the sum of the two numbers. Generaly a promise can also be rejected.

Asynchronic Test-Step

When we come to test a method that returns a promise, we need the test-step method to return a promise too. One of the simple ways to do this, it by defining the test-step method as async method, and calling the method to test with await keyword.

@it('should test a promise with async await')
async addWithAsyncAwait(): PTR {
    let result: number = await addPromise(1,2)
    expect(result).to.equal(3)
}

Note: PTR (Promise Test Result) is the return value of async test-step. Not relevant at this point.

Note that the test-step is defined async and therefor returning a promise itself. The test-step will be finished only after the promise is resolved of rejected (no need for done method). If the tested method (addPromise) returns a promise that is rejected, the error will pass to the test-step promise, that will be rejected itself, and cause the step to fail.

Chai As Promise

soda-test includes a plugin of chai, that allows you to directly validate the a result of a promise, by using the eventually property

@it('should test a promise with chai-as-promise')
async divideWithChaiAsPromise(): PTR {
    await expect(dividePromise(4,2)).to.eventually.equal(2)
}

You can also use this to check a rejected senario

@it('should fail to divide by 0')
async divideFails(): PTR {
    await expect(dividePromise(4,0)).to.eventually.rejectedWith('cannot divide by 0')
}

Note that when you use the eventually property you must also use the await keyword before the expect method.

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