I’m starting to test my code with Jest, and I can’t make a seemingly simple test to pass. I am simply trying to check if what I receive from a Maogoose database request is an object.
The function fetchPosts()
is working because I hooked it up with a React frontend and it is displaying the data correctly.
This is my function fetchPosts()
:
module.exports = { fetchPosts() { return new Promise((resolve, reject) => { Posts.find({}).then(posts => { if (posts) { resolve(posts) } else { reject() } }) }) } }
And my test:
it('should get a list of posts', function() { return posts.fetchPosts().then(result => { expect(typeof result).toBe('object') }) })
This makes the test fail, and Jest says
‘Timeout – Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.‘
QUESTION: How can I make this test pass?
Advertisement
Answer
You can expect asynchronous results using resolves
, as shown in the Jest documentation.
In your case:
it('should get a list of posts', function() { const result = posts.fetchPosts(); expect(result).resolves.toEqual(expect.any(Object)); })
…although I have a suspicion your list of posts is actually an array, so you probably want this:
it('should get a list of posts', function() { const result = posts.fetchPosts(); expect(result).resolves.toEqual(expect.any(Array)); })
Another tip: You don’t need to wrap the body of your fetchPost
in an additional promise, you can simply return the promise you get from Posts.find
and add a then
to it, like this:
module.exports = { fetchPosts() { return Posts.find({}).then(posts => { if (posts) { return posts; } throw new Error('no posts'); // this will cause a promise rejection }) } }