Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest testing with Node - Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout

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?

like image 629
mokiliii Lo Avatar asked Nov 20 '18 16:11

mokiliii Lo


2 Answers

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
        })
    }
}
like image 198
Patrick Hund Avatar answered Oct 28 '22 14:10

Patrick Hund


It's also highly possible that you're not getting a response back from the DB at all from your test suite. Test suite's can call different environmental variables / configs that lead to different calls. This error can also be seen if no response is returned, as in - if someone blocks your IP from connecting, on and on.

like image 23
typo Avatar answered Oct 28 '22 13:10

typo