I am trying to do unit testing for a simple function which sends a get request, receives a response and then returns a promise object with the success or the failure message. Following is the function:
module.exports.hello = async (event, context) => {
return new Promise((resolve, reject) => {
fetch("https://httpstat.us/429", { headers: { 'Content-Type': 'application/json' } }).then(response => {
console.log(response);
if (response.status == 200) {
return response;
} else {
throw Error(response.status + ": " + response.statusText);
}
}).then(tokenData => {
resolve({ status: 200, body: JSON.stringify({ statusText: 'Success' }) });
}).catch(error => {
reject(error.message);
});
});
};
While unit testing, I am using fetch-mock to mock the call to the api and have a custom response. Following is the code:
it('hello returns failure message', (done) => {
fetchMock.get('*', {
status: 429,
statusText: "Too Many Nothings",
headers: { 'Content-type': 'application/json' }
});
edx.hello(null, null).catch(error => {
expect(error).to.equal('429: Too Many Requests');
}).then(() => {
done();
}).catch(error => {
done(error);
});
});
But this code is not mocking the fetch request as when I print the response text it is "Too Many Requests" which is being sent as a response by the API and not "Too Many Nothings" which is being mocked. I am new to NodeJS. Please tell me what am I doing wrong.