Introduction to Jest Testing

Introduction
Testing is one of those things that people either love or hate. Usually testing is something that is hated, until you work on a project with good tests, and you realize how amazing they are. In this tutorial I am going to show you how to get started with testing in JavaScript using Jest. I will talk about the code you need in order to write tests, as well as show you some pitfalls of testing. At the end of the video I will break down the importance of testing and some best practices you can adhere to in order to make your tests incredible.
How to Install Jest
make project folder and cd into it
initialize npm
this will set up the initial project structure and create package.json
install jest as a development package
NOTE: saved as a development dependency only because only used during development
change the test script inside the
package.json()
file and replace existing test script with"jest"
Why Testing is Important
Be confident that your code works. You make a bunch of changes, when you test your code, and it still passes those test, then you are more confident in your code. But what happens when you don't test, and then you deploy your code. It becomes unstable and your users start to complain that it is not doing what they need it to do.
Make better architectural decisions. It will help you structure your code better and achieve proper separation of concerns. You won't be tempted to assign multiple responsibilities to single code blocks as those would be a nightmare to unit-test.
Pinpoint functionality before coding. What should happen in case a parameter is null? What if its value is outside the expected range or contains too many characters? Do you throw an exception or return null? Unit tests will help you discover all these cases. Look at the questions again, and you'll find it's exactly what defines your unit test cases. reference freecodecamp.org
How to Write Unit Tests in Jest
create a file and name it the same as the file you want to test i.e.:
How to write a test
Step 1. Import file you want to test
Step 2. Set up your describe block
Step 3. Run the test
— First argument passed in actually will get displayed inside the console when you run the test
— Second parameter is the callback function that actually runs the test
— Inside the callback you use the expect function that is the actual test - `expect()` returns an expectation object
— `.toBe()` is the matcher that is called on the returned expectation object - the correct value you expect to be returned by the function you are invoking inside the expect function is passed into the matcher
— When jest runs, it keeps track of all the matchers that fail and prints out nice error messages for you—for a complete list of jest matchers
The Importance of Test Coverage
it's good to cover as much code as possible with tests
will tell you how big a portion of your code is covered by unit tests