Adding tests to our package can ensure it works as expected. We will install a test framework
jest. We will then create a
test script to run our tests. Then we will create a
test:watch script to keep tests running while we develop.
Let's run nom install Jest, and then save that to our development dependencies. Now if we look inside of our package.JSON inside of the dev dependencies we have this new Jest package listed.
Now in our scripts we can use that. We have this test script defined which is just the default echo statement. Let's change that to run the Jest binary. Now when we run the test script, this Jest command is going to run. Let's go into our source directory and we want to test this file here.
I'm going to create an index.test.js file, and this .test.js extension is one of the patterns that Jest recognizes by default. Inside the file we could import our module which we'll call "sensitive words" from the sibling file. Because the sibling file is in the current directory and its named with an index.js, this single dot will find it.
Now we can write our test, so we'll say test. Then we'll need a description of the test as well as a function to run.
For the description right now let's check that it says, "Hello world." Now we can say, expect that when sensitive words is run that it gives us, "Hello world."
For another pane I can say, "nom test," and our test is failing. If we scroll up it says that it's not saying, "Hello world." We expected "Hello world" and we got "Hello universe." Let's go check our source file, and our source file is saying, "Hello universe" currently. Let's change that to "Hello world," save the file. Now we can rerun our test script and it's parsing.
Let's go back to our package.JSON and underneath our test script let's make a new script called "Test watch." We can have this run the test script and parse it the watch flag, which is the option that Jest provides for automatically watching tests. Now we should be able to run npm run test watch, and our tests are parsing as well as continuing to run.
If we go back to our test file and change "world" to be "universe" again, if we run this our tests will be failing. We can open up our source file and change the world to be universe as well, and save that. Now our tests are parsing again. Now we can run our tests in watch mode and have our source files and tests all working together.