We will run our
test:watch scripts to develop; we will create some tests for the expected functionality of our package; it should conceal any words in a string that are in a blacklist of words. Then we will write the logic to make those tests pass.
I've opened three terminal panes. In one of them, I'm going to run npm run dev to automatically compile my source code.
In another, I'm going to run npm run test watch to automatically run my test. In the last pane, I'm going to develop my features for my package.
Let's go and open up our source test file. Let's change the description to "Replaces blacklisted words with asterisks." For our sensitiveWords() call, for the first argument, we'll pass a string that we want to filter. We'll say, "The name of the NX will be the Nintendo switch."
For the second argument, let's pass an array of words that we want to filter, so if Nintendo didn't want people to know about the names switch, they could put switches of a blacklisted word.
Now, when we run this, we're going to expect that this returns the same string, but with the switch replaced with ***. I'm going to format this, a little bit, so that it's easier to read. Put the first argument here, and then the second argument on the next line.
If we save this now, we haven't written the code to make this work, so our tests are definitely failing. We expect to get this string with the word, switch, replaced with asterisks, and we're getting back "Hello Universe."
I'm going to go into my index file and our first argument is going to be the content that we want to check. Our second argument will be the words that we want to filter with asterisks.
Now, we can remove this "Hello Universe" and add a multi-line return. We'll say content.replace and our first argument is going to be a regular expression.
Our second argument will be ***. Inside of our regular expression, our first argument should be words.join| For the second argument, we need to give it the flags we want to use. Let's use i for ignore case, so that both capital and lowercase switch get replaced.
If we save that, it shows that our tests are passing.
Let's go back to our test file, copy this test, and write another one. I'll paste that and then change the description to say, "Replaces multiple instances of blacklisted words." Let's add onto our test string to say, "Switch will be awesome."
Let's update our expected output to say, "The *** will be awesome." We expect the switch here and the switch here to both be replaced with asterisks.
If we save that, it says that "Tests are failing." The first switch got replaced but not the second.
If we go back to our code, it looks like we need to update the flags of the regular expression to include the global flag, so that each match in a line is replaced.
Let's save that. Now our tests are passing.