Reputation: 637
I'm struggling with Jest, I just can't get it to work properly.
Function I wanna test:
fetchPosts() {
return new Promise((resolve, reject) => {
Posts.find({}).then(posts => {
if (posts) {
resolve(posts)
} else {
reject("NOOOO")
}
})
})
}
Test:
describe('fetching posts', () => {
it('should get a list of posts in Array format', () => {
expect.assertions(1);
const result = posts.fetchPosts();
return expect(result).resolves.toEqual(expect.any(Array));
})
})
The fetchPosts
function does return the whole list of posts. How can I make my test pass?
Upvotes: 1
Views: 4057
Reputation: 302
Your fetchPost function is asynchronous. To make it work in your test you need to change some things.
Add 'async' to your test
it('should get a list of posts in Array format', async () => {...})
Add 'await' before you call your async function
You need to expect()
the result you want to get back from your function without the return statement.
Upvotes: 1