Jasmine has Asynchronous Support which uses "function + done" formular. This spec will not start until the done
function is called in the call to beforeEach
. And this spec will not complete until its done
is called.
beforeEach(function(done) {
setTimeout(function() {
value = 0;
done();
}, 1);
});
it("should support async execution of test preparation and expectations", function(done) {
value++;
expect(value).toBeGreaterThan(0);
done();
});
As Jasmine doesn't support native async/await at present, we need to do some extra works to make Jasmine to support it.
-
Use jasmine-co
// spec/helpers/jasmine-co.helper.js require('jasmine-co').install(); // spec/bookService.spec.ts describe("user models", function() { beforeEach(async function(){ this.user = await getUser(1); }); it("should be able to get a list of owned books", async function() { var books = await bookService.getBooksForUser(this.user); expect(books).toEqual(jasmine.any(Array)); }); });
-
Wrap async function:
it('should run test', done => { (async () => { let title = await browser.getTitle(); // assertions done(); }).catch(done.fail); });
-
Use a testing helper:
// The helper function function testAsync(runAsync) { return done => { runAsync().then(done, e => { faile(e); done(); }); }; } // Spec it('should run test', testAsync(async function() { let title = await browser.getTitle(); // assertions }));
Protractor uses jasminewd2, which provides the following features:
- Automatically makes tests asynchronously wait until the WebDriverJS control flow is empty.
- If a
done
function is passed to the test, waits for both the control flow and until done is called. - If a test returns a promise, waits for both the control flow and the promise to resolve.
- Enhances expect so that it automatically unwraps promises before performing the assertion.
So in Protractor, we can just use async/await naturally:
beforeEach(async () => {
await browser.get(theUri);
});
it('should run the test', async () => {
let title = await browser.getTitle();
// assertions
});
Thanks for the great gist. I have a question though, with the latest jasmine, it supports native async support and as you have mentioned in the Protractor, you can simply use the similar way to write an async test like follows:
which is pretty cool.
But, in this case, we are not handling any errors like you do in the previous section in catch.. How, can I do error handling here so that I can log my error messages to the console which would help me in debugging?
Thanks.