The problem I'm seeing in your code is that expect().toThrowError() expects an synchronous exception, but your code is actually rejecting a promise. The bit that may be confusing is that you see throw new Error('foo'); in your handleResponse. That's throwing an exception, true. However, because this code is called by an async function this exception is converted to a promise rejection. So await get('sampleUrl') does not result in a synchronous exception being thrown but in an asynchronous promise rejection.
Looking at Jest's documentation, it seems to me that you should be doing:
return expect(expectedError()).rejects.toThrowError();
You need to call expectedError because it is a function that returns a promise, and you need to use .rejects to converts the rejection to a plain exception that can be tested with .toThrowError(). Make sure to return the assertion, or await it. Otherwise you'll have dangling promise.
» npm install axios-mock-adapter
Expecting an error with axios-mock-adapter
unit testing - How do you verify that a request was made with axios-mock-adapter? - Stack Overflow
Newest 'axios-mock-adapter' Questions - Stack Overflow
React-Testing-Library - What do you guys use to mock HTTP requests?
Videos
Note: This answer is now outdated, see this answer by Laszlo Sarvold instead.
axios-mock-adapter does not appear to have this functionality built in to it, however if you are using jest, you can use jest.spyOn.
For your example above
let spy = jest.spyOn(axios, "get");
//run http request here
expect(spy).toHaveBeenCalled();
Note: depending on what you are using, you may have to wrap your expect statement in setTimeout(function, 0) for it to work properly
As per https://github.com/ctimmerm/axios-mock-adapter there is an out of the box functionality for verifying request calls:
expect(mock.history.post.length).toBe(1); // times called
expect(mock.history.post[0].data).toBe(JSON.stringify({ foo: "bar" })); // posted object
I tried:
axios-mock-adapter
Axios test fails when you use a proxy in your package.json.
Error: connect ECONNREFUSED 127.0.0.1:80
Other then that, it works great. But I'm unable to use my CI because it outputs the error above too.
Nock
Works great, but I can't seem to mock requests with headers sent (such as authorization). I find it hard to find information on how to solve the issue.
I'm wondering if there are other libraries I should try out (or bonus points if there is a solution to the problems above :)!