Intro
Understanding the basics of unit testing with generic functions as an example. Let's write several tests and learn unit tests!
Prelude
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:
Loading
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.
Loading
Let's add the implementation for tests.
Loading
Congrats! You know the basics!
Different convention
I think it's bad when developers using implementation details or refers to an API in test names.
Loading
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.
Loading
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.
Summary
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
10 minutes
Software testing
2 m
Grouping the tests
1 minute
The usage of describe and it
2 m
The best practices for naming tests
2 m
Navigating the different types of software tests
3 m
- 2. Mastering unit testing
38 minutes
Project and tests setup
3 m
Unit tests review
4 m
React component testing
5 m
Snapshot testing in React
4 m
Understanding stubs in testing
3 m
Understanding mocks in testing
5 m
Creating testing fixtures
4 m
Using spies in React and Typescript
3 m
Mocking environment variables
3 m
Using dependency injection pattern to improve fixtures
4 m
- 3. Mastering integration testing
12 minutes
Understanding the integration tests
4 m
Using MSW library to remove implementation details from tests
4 m
Creating fixture for MSW to reduce boilerplate and setup
4 m
- 4. Mastering e2e tests
8 minutes
Comments
Add your honest opinion about this article and help us improve the content.