Understanding the basics of unit testing with generic functions as an example. Let's write several tests and learn unit tests!
Let's try to use theory in practice. I'm assuming that you have already a project with testing environment configured.
Your first unit tests
I'm 100% sure that you've used in your career map function. Let's try to write our implementation and later we'll add unit tests.
If you're curious about performance of map, reduce and other abstractions you can check our article in which we compared them.
Take a look at following implementation of map:
Usage looks a little bit different than in Array prototype but mechanism is the same. Now we can add our unit tests. We'll use conventions from this lesson. Let's try to imagine what we want to verify - same situation like in our restaurant metaphor.
Let's add the implementation for tests.
Congrats! You know the basics!
I think it's bad when developers using implementation details or refers to an API in test names.
Why I think it's bad?
- Work is doubled in every rename attempt
- The focus is on implementation - not on the purpose of something
- Test descriptions are not clear
- Typos risk
You can improve that by removing references to the implementation and to the API shape. It will reduce amount of time to maintain code and will make tests like documentation.
Sometimes you need to embed implementation details or API reference in descriptions. You will know when it happens. If you have problems with creating description that's 99% the case where it's better to point to implementation details.
Remember - I'm not saying it's best practice. I'm using this approach and I pointed out arguments why. Try it and create your own opinion.
That was quick! Now we know how to test simple generic functions. Sadly, testing is much more complex. We need to dive into details in next lessons. So stay with us!
If you enjoyed it, be sure to visit us on Linkedin where we regularly upload content from programming.
- 1. Basics
Grouping the tests
The usage of describe and it
The best practices for naming tests
Navigating the different types of software tests
- 2. Mastering unit testing
Project and tests setup
Unit tests review
React component testing
Snapshot testing in React
Understanding stubs in testing
Understanding mocks in testing
Creating testing fixtures
Using spies in React and Typescript
Mocking environment variables
Using dependency injection pattern to improve fixtures
- 3. Mastering integration testing
Understanding the integration tests
Using MSW library to remove implementation details from tests
Creating fixture for MSW to reduce boilerplate and setup
- 4. Mastering e2e tests