We have all been hearing about the importance of writing tests and test-driven development.
✅ Here's how you can write better tests by implementing the testing pyramid strategy.
- Unit Tests
- Integration Tests
- End to End Tests
Testing pyramid tells you what type of tests you should be more focussed on.
A unit test verifies that an individual piece of code functions as expected. They don't have any external dependencies.
Unit tests form the base of the pyramid. Ideally they should constitute bulk of your tests.
They are quite fast to execute, hence devs are encouraged to run it as often as required.
Next layer on the pyramid are the integration tests.
Integration tests validate how a piece of code functions when it interacts with other code. These tests communicate with external dependencies like database's & external API's.
They are slow compared to unit tests. They also need the external services to be running.
At the top of the pyramid, we have End 2 End tests.
These tests interact with pages just like a user would, for example by clicking buttons and typing into text boxes, and they check that pages respond appropriately from the user's perspective.
They test the functioning of an app in its entirety. They are the slowest to run and given its dependency over multiple things, they are non-deterministic in nature. Ideally, you should be having only a few of these.
They are non-deterministic, the automation software must wait for the browser to complete the page load and for the particular element to appear.
For example, suppose that you write a test that clicks a button to open a modal and then clicks a button inside the modal to close it. Sometimes, the modal will open before the test tries to click the close button, so the test will pass.
We've looked at the types of tests above.
At a broad level, there are 2 aspects of a test type.
- Test surface
You can see that speed is inversely proportional to the test area. Unit tests cover a short area, hence they are fast to run. But they cannot guarantee the functioning of a feature from the perspective of a user.
On the other hand E2E tests, validate the functioning of an entire feature as an end user would use it, but they are very slow to run and have lot of dependencies.
A good test suite will have a mix of the 3 types of tests outlined above. Unit tests are more reliable and fast, on the other hand E2E tests verify the functioning of an entire app, but are slow and non-deterministic.