How To Unit Test A Rest Service
My little self stood in front end of my calculator some years ago, churning out code that today would make me scream like a babe deprived of nutrient. The motivated me had made some changes to a i,000-line app the previous night, and now the code just wouldn't run. If at that place was anything I retrieve, it was asking myself, "How do people build apps that are easy to modify?" This was a question I solved by myself a few months later. And the reply is cipher other than rigorous and automated tests done the right way.
When we buy a new pair of shoes, we test them out—we try them on to see if they fit. Considering it's through testing that we infer the quality of products. A quality REST app is an indication of rigorous testing done correct. In this postal service, I'll testify you three ways y'all should be testing your Residue application.
Why Writing Tests Is Important
There are several good reasons to write tests:
- We don't write code one time. Working code changes oftentimes. It's through refactoring that we continuously improve a code base and design. Tests are controls that ensure that the intended behavior is preserved while y'all implement your changes.
- When y'all refactor lawmaking, you desire to brand sure you're not accidentally modifying an existing beliefs. Without tests, it'south difficult to know when you cross the boundary of refactoring.
- Tested lawmaking gives confidence. Nothing is as terrible as customers finding the problems you should take detected during tests. The more automated tests y'all accept in your lawmaking, the more confident you lot become.
- Some bugs are very difficult to take hold of, regardless of how good of a programmer you lot are. We're all humans, and nosotros brand mistakes. Automated tests help you find these bugs early on.
3 Types of Tests You Should Be Writing
Let's say you're building a new eastward-commerce app in Node.js. This application would allow users to browse products and place orders. Unremarkably, an e-commerce app is composed of many modules and components, similar catalog service, cart service, payment service, and a data store.
I matter you could do is build a consummate app and later on perform a manual functional test by clicking every nook and cranny to confirm that it works as expected. In the finish, not only would yous terminate up with a low-quality, buggy application that'southward breakable, only the building process would be highly frustrating equally well.
What if y'all had some automated ways to verify that every bit of your code works as you lot code? An automated test compares an actual consequence with the expected outcomes.
The term "testing" tin can exist ambiguous and often means different things to different people. The fact that dissimilar kinds of testing exist doesn't help the matter. Even if yous know a few kinds, chances are in that location are many you might not fifty-fifty know exist. In this post, nosotros'll focus on the test pyramid—the iii layers of tests you should accept in your test suite and how to write them.
Mike Cohn came up with the concept of the test pyramid, a strategy for having a proper balance of automatic tests on different layers of an application.
A exam pyramid looks similar this:
The test pyramid has three layers: low-level unit tests, middle-level integration tests, and high-level end-to-stop (UI) tests running through a graphical user interface. Ideally, yous should take more low-level unit of measurement tests than loftier-level UI tests.
Simply await a minute! What do I mean by a unit exam, and how does fit into your test suite? Read on to find out.
Unit Examination
Developers often have different ideas near unit of measurement testing; the individual expectation of what a unit test should be varies. Near of the fourth dimension, the differences aren't in the framework used in testing. Instead, the differences lie in what's considered to be a unit of code.
In some cases, I've seen the broad line betwixt unit of measurement examination and integration test become so sparse and sometimes disappear. One could ask, how can I test my APIs? If I write tests for a REST API endpoint, am I also doing unit of measurement testing?
No, y'all're non, and here'south why.
A unit test verifies a small portion of your lawmaking independently from other modules of your awarding. If y'all're not writing a "Hello World" app, usually your app will contain services and modules that are interconnected.
A unit examination doesn't test a module as a whole. It tests the smallest units that make up a more than significant module.
What to Test in Unit Testing
A unit of measurement test could assert that a method:
- Returns an expected value
- Throws an exception under the tested condition
- Changes the land of the system
- Calls another function
Isn't it okay just to exam the module and leave the unit of measurement of work? Again—no, it'southward not! It'southward the unit of piece of work that makes upwardly a module. The nastiest problems I've seen in production as an engineer happened at the unit of measurement level. If your code suffers defects at the unit level, it'll propagate to your entire application.
For case, you retrieve the hypothetical e-commerce app we discussed earlier. Permit's say we have a cost reckoner module responsible for calculating the price of a production, including the shipping fee. For simplicity, nosotros could strip this module down to something that looks like this:
A unit examination would examination that role shippingFee() returns xx% of the base of operations price. Let's take a moment to write a simple unit test for this method using Jest. Jest is a JavaScript testing framework created at Facebook.
If y'all look at the code to a higher place, we're not testing the PriceCalculator behavior with respect to other services in the application. Nor are we testing the entire module; we're testing a unit of work (a method) independent of other modules.
Because a unit of measurement test does examination a unit of code, information technology's normally fast, and it always should be. If your unit tests take longer to run, chances are you're doing something incorrect.
Now that nosotros've seen what a unit of measurement test should be and how to write information technology, it's besides essential that you examination that your code still works later integrating with other components. Could in that location be a chance of conflict afterwards integration? Nobody knows, and this why you should also write integration tests.
Integration Exam
Working software consists of different modules and components in synergy. From the database layer down to the presentation layer, i component depends on another. The more interconnected the parts, the higher the likelihood of conflicts or something going wrong. An integration test combines individual units of work and tests them as a group. Information technology could be testing that when a user accesses a path with the ID of a product, the product details are returned as JSON.
In an east-commerce app, you may want to return production details when a user clicks on an item. In that location could exist many things going on nether the hood. For example:
- A database service may retrieve the product details from the database.
- A pricing service could calculate the product price and shipping fee, taking the user'southward location into play.
- An analytics service could rails user interaction with the product.
Assuming the snippet below does all of these, an integration test will test that these components work well together.
Let'southward take a moment to see how we could test this endpoint using supertest, a node parcel that allows yous to examination HTTP servers.
The test would wait similar this:
When you perform integration testing, it's important that you verify:
- The HTTP condition lawmaking
- The response payload
- The response headers
- The API operation/response time
That said, let us explore the UI test.
UI Tests
In the examination pyramid, the UI examination stands at the acme because it's the type of test you lot write afterward all modules and components accept been integrated. Different the unit test or integration test, a UI test isn't limited to a module or a unit of your application; it tests your application as a whole. It simulates real user actions.
Information technology's a examination performed to define that an app runs every bit expected and meets the system requirements. It's the slowest and the most expensive exam because information technology replicates real user deportment in the browser. Y'all can't write good UI tests without a total understanding of your app's requirements and end goals.
A UI exam for our e-commerce app could verify that users tin admission the homepage and, within a certain amount of time, click on a link to view a product. We could do this with Nightwatch.js , an finish-to-terminate testing bundle for Node.js apps, every bit follows:
Conclusion
In conclusion, the UI tests verify that the overall system meets requirements, merely they're slow, expensive, and can inhibit your agility. Hence, you should write more low-level tests and proceed your UI tests lean. Integration tests prevarication in the middle of the pyramid. Although they don't go into details of the app as much as UI tests exercise, they're good for pinpointing when integration between components leads to undesired behaviors. On the other manus, unit tests are fast, cheap, easy to write, and efficient. They're quick to bear witness where things go incorrect simply not good at detecting misbehavior on the integration level.
Finally, if you desire to take a look at the code used in this postal service, yous can find it here.
This mail was written past Samuel James. Samuel is an AWS solutions builder, offering 5 years of experience building large applications with a focus on PHP, Node.js, and AWS. He works well with Serverless, Docker, Git, Laravel, Symfony, Lumen, and Vue.js.
What to read next
React Native Unit Testing: A Complete Getting Started Guide
Unit Testing All-time Practices: vi to Ensure Y'all Do Information technology Right
How To Unit Test A Rest Service,
Source: https://www.testim.io/blog/unit-test-rest-api/
Posted by: williamsletly1959.blogspot.com
0 Response to "How To Unit Test A Rest Service"
Post a Comment