Test Asynchronous Code
Learn when to use async/await syntax to test asynchronous code.
We'll cover the following...
Asynchronous code runs as a callback function, for example, after a timeout or interval. The best way to run asynchronous code in modern JavaScript is using the async
/await
notation. Jasmine makes this easy to test. Look at the example below, where we await
the result of the loadPosts
method before making our expectations.
function loadPosts() { return new Promise(resolve => { setTimeout(() => { resolve([{ id: 1, title: 'First post', content: 'This is my first post', }]); }, 2000); }); } describe('Blog page tests', () => { it('Returns users created in past year', async () => { let posts; posts = await loadPosts(); expect(posts.length).toEqual(1); expect(posts).toEqual([{ id: 1, title: 'First post', content: 'This is my first post', }]); }); });
The async/await syntax
In this example, we have a loadPosts
method defined ...