How to solve promise() is not a function

Viewed 2370

I have React code that makes API call to a backend server. I am trying to test it using Jest.

Let's assume I have a class 'User' with a single method listResources.

User user = new User(credentials);

user.listResources()
    .promise()
    .then(res => console.log(res))
    .catch(err => console.log(err))

I am mocking it in my Jest tests like this:

User.prototype.listResources = jest.fn().mockImplementation(
        () => {
            return new Promise((resolve, reject) => {
                resolve('resourceA');
                reject('error');
            })
        }
)

The test returns

TypeError: user.listResources(...).promise is not a function

Any ideas on how to approach this?

1 Answers

listResources is expected to return an object that has a promise function, so you need to mock it like this:

User.prototype.listResources = jest.fn(() => ({
  promise: () => Promise.resolve(), // or Promise.reject()
}));
Related