mokiliii Lo
mokiliii Lo

Reputation: 637

Expected one assertion to be called but received zero

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

Answers (1)

Fabian Hinsenkamp
Fabian Hinsenkamp

Reputation: 302

Your fetchPost function is asynchronous. To make it work in your test you need to change some things.

  1. Add 'async' to your test

    it('should get a list of posts in Array format', async () => {...})

  2. Add 'await' before you call your async function

  3. You need to expect() the result you want to get back from your function without the return statement.

Upvotes: 1

Related Questions