Now that we've set up the basic structure for our project, we can start setting up the testing framework
Before we do that, let's pause to examine test-driven development (TDD) in more detail.
TDD is a software development practice in which a developer creates failing test cases, and then writes code so that the tests pass.
Red, Green, Refactor.
It's important to note that TDD isn't simply about adding tests. It encompasses the process of writing tests before you write a single line of code, and then writing code in small increments.
We'll use the Jest framework for the tests we writ
First, run npm install jest --save-dev. The --save-dev flag tells npm to add Jest to the devDependencies list.
. If we already had a package.json file with both dependencies and devDependencies properties, running npm install would install all packages from both lists.
npm scripts allow us to add short snippets that we want our project to run at different stages during the build that we would otherwise run from the command line.
All other scripts must follow the convention: npm run <scriptname>. For more details, visit the npm docs (Links to an external site.).
Technically, you could—but adding scripts to package.json allows other developers to join the project without needing to know exactly which commands are run to build and test the application.
We separate all our tests into their own folder so that we can clearly differentiate between the application code and testing code.
Let's create our first test! We'll start with a simple one.
In the __tests__ directory, create a new file named random.test.js. We use the *.test.js naming convention because this is what Jest expects. This also helps us keep things organized, since our test file has a different name than our constructor file
Did you notice that the test reads almost like plain English?
it should be very clear to anyone what the test is checking for and whether it passed
Right now, our test doesn't pass. If you run the test with the command npm run test, it will fail, due to checkIfEqual() not being a function. This is expected because the file random.js doesn't exist yet.
We still need to add a line to lib/random.js so that checkIfEqual refers to a module.
There's still one more step in TDD—the refactor step. This one leaves the most room for interpretation.
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.