Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JEST - why mock api calls?

I'm getting familiar with JavaScript testing, and may be missing a point or two related to mocking api calls. Every tutorial I have found mocks api calls when doing unit or integration testing - example: https://jestjs.io/docs/en/tutorial-async

I dont understand the value of mocking a server response by providing hard coded data, and then testing the value of that hard coded data. It seems like all such a test does is tell you whether or not your tool used a mock instead of an actual api call. That result doesn't tell you anything about the behavior of your application though does it not? Am I missing something?

Additionally, what if I wanted to actually test the result of a real api call? Does that push me over into functional testing territory? Could a real test of an api call be done with a tool like Jest, or is that better suited for something like selenium or testcafe?

like image 639
Winston Smith Avatar asked Feb 06 '19 19:02

Winston Smith


People also ask

Should I mock API calls?

However, whether your API is still in development, or you are working on new features, testing expected behaviors systematically can save a lot of time and make it easier to identify problems. Developing mock API calls can help you use valuable unit tests, without the problems associated with calling a live API.

Why do we mock API?

Why Use API Mocking? A mock API server is useful during development and testing when live data is either unavailable or unreliable. While designing an API, you can use mock APIs to work concurrently on the front and back-end, as well as to gather feedback from developers.

Is Jest good for API testing?

Jest is great for validation because it comes bundled with tools that make writing tests more manageable. While Jest is most often used for simple API testing scenarios and assertions, it can also be used for testing complex data structures.


Video Answer


2 Answers

If you want to test a call to a real api, and if that call is done by a front-end application, TestCafe offers Request Hooks that enable to check that the api is called in the right way and that the response contains the right data.

Mocking an API Response enables to do some kind of chaos testing: what happens to the front-end when API sends an HTTP 500/400/404/202/... or when the API never sends a response...

like image 83
hdorgeval Avatar answered Sep 30 '22 03:09

hdorgeval


That result doesn't tell you anything about the behavior of your application though does it not

Sure it does. It tells you your front end component was able to correctly handle the received data (put it in a redux store, localStorage, update the UI, etc).

like image 27
Adam Avatar answered Sep 30 '22 02:09

Adam