August 2017
Beginner
374 pages
10h 41m
English
If you use promises instead of callbacks, like we did in our project, Jest provides an easier way to handle asynchronous tests. You can simply return a promise from the test, and Jest will wait for it to resolve. If the promise is rejected, the test will automatically fail. Let's assume our fetchPosts function returns a promise now. Then, our test would look as follows:
test('fetchPosts returns array of posts', () => {
We will use another matcher here, to ensure that a certain number of assertions are called during a test. This is useful when dealing with asynchronous code:
expect.assertions(1)
Then, we simply return our promise and check the result:
return fetchPosts() .then(posts => expect(posts).toContain({ title: 'test' })) ...Read now
Unlock full access