For those who may not know, Jest is a library used for testing.
yarn add --dev jest
npm install --save-dev jest
I'm not going to get into the nitty-gritty details of setting it up and every feature that comes along with the library. I'd like to keep this post relatively short and review some simple use-cases. If you're interested in more details you can check out the official docs at https://jestjs.io/
In the below snippet I've created 2 simple functions in a single file. These will add and subtract whatever numbers are passed in.
For testing purposes, you'll want to make sure you export the functions so they can be used in our separate testing file.
Now that we've created our functions, we want to test them using Jest. You'll want to create a separate file with the following name filename.test.js.
By including the .test in the filename, this tells Jest which files to run.
Let's go ahead and run some simple tests against our Add and Subtract functions.
In the below snippet you'll see how the tests can be written.
Now, what's going on here?
The test function takes in a string. This string is essentially the description of what the test is doing, or what the expected outcome is. As you can see, I quickly described what numbers I am adding/subtracting and the expected result.
The second part of the test function is where you'll actually execute your imported functions.
We use the expect function to execute our Add/Subtract function with 2 numbers passed in as arguments. We then follow with a "matcher" function. In this case, the matcher function is .toBe. What this is doing is expecting the result of the function to be whatever argument is passed into the .toBe matcher function.
To run your test in the console you can write:
npm run test
This will be dependent on how the script is written in your package.json file.
In this case, when 2 and 5 are passed into the Add function it's expecting the result to equal 7. If the function returns anything other than a 7 the test will fail.
The same goes for the Subtract function in regards to whatever numbers you pass into it.
This allows us to ensure that our functions are working properly. It also reduces the chances of running into issues within our application down the road.
Testing is a very important part of being a developer, especially when you start building more complex applications.
You want to ensure that your programs are working as they should be, and you can achieve this by writing tests.
Thank you for taking the time to read this and I hope it was helpful.