JavaScript Testing: Jasmine async syntax

JavaScript Testing: Jasmine async syntax

Need 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.

Finally instructions on how to configure Babel for async/await in tests.

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).

beforeAll(done=>{// The same construct can be used for// beforeEach, afterEach and afterAlldone();},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",()=>{vartimePassed=0;setTimeout(()=>{timePassed+=100;},100);expect(timePassed).toBe(0);jasmine.clock().tick(100);expect(timePassed).toBe(100);});it('can hijack new Date',()=>{constbaseTime=newDate(2013,9,23);jasmine.clock().mockDate(baseTime);jasmine.clock().tick(50);expect(newDate().getTime()).toEqual(baseTime.getTime()+50);});afterEach(()=>jasmine.clock().uninstall());

Async Await

For the really hip people, and with a little help of .babelrc, you can write your tests like: