JavaScript Testing: Jasmine async syntax
posted in javascript on • by Wouter Van Schandevijl • last updated onNeed to test async code? No problem for Jasmine.
There is done()
to inform Jasmine a test has finished running.
With jasmine.clock()
, the value of new Date()
can be manipulated.
Example
it
, beforeEach
, afterAll
, … have an additional optional parameter called timeout (ms).
A test fails for such a block when nor done()
nor done.fail()
is called within
jasmine.DEFAULT_TIMEOUT_INTERVAL
which defaults to 5000 (ms).
it('can use async/await', async () => {
const pie = await Promise.resolve(3.14);
expect(pie).toBe(3.14);
});
beforeAll(done => {
// The same construct can be used for
// beforeEach, afterEach and afterAll
done();
}, customTimeout);
it('has an optional "done" parameter', done => {
Promise.resolve()
.then(() => expect(true).toBeTruthy())
.then(done)
.catch(done.fail);
});
xit('can fail with a specific message', done => {
Promise.reject().catch(done.fail.bind(this, 'done.fail("with your error message")'));
}, customTimeout);
Time Travel
beforeEach(() => jasmine.clock().install());
it("doesn't have to take the slow path", () => {
var timePassed = 0;
setTimeout(() => {
timePassed += 100;
}, 100);
expect(timePassed).toBe(0);
jasmine.clock().tick(100);
expect(timePassed).toBe(100);
});
it('can hijack new Date', () => {
const baseTime = new Date(2013, 9, 23);
jasmine.clock().mockDate(baseTime);
jasmine.clock().tick(50);
expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
});
afterEach(() => jasmine.clock().uninstall());
expectAsync
it('can check for resolved', async () => {
const pie = Promise.resolve(3.14);
await expectAsync(pie).toBeResolved();
return expectAsync(pie).toBeResolvedTo(3.14);
});
it('can check for rejected', async () => {
const pie = Promise.reject('reasons');
await expectAsync(pie).toBeRejected();
await expectAsync(pie).toBeRejectedWith('reasons');
});
it('can pass context - which will show on failure', async () => {
const pie = Promise.resolve(42);
await expectAsync(pie).withContext('test').toBeResolved();
});
Stuff that came into being during the making of this post
Updates
- 28 March 2023 : Updated to Jasmine 4.3.0.
- 18 January 2019 : await/async is pretty standard now. Added expectAsync examples.
Category:
javascript
Tags:
tutorial
testing