Making our code fail

It is important to know that we won't use any testing framework at this point. The main goal in this section is to understand how TDD works; we have a complete tour of testing technology in the following sections in this chapter.

We will use TDD to create an additional function called sum, which will return the sum of two numbers that are passed as parameters. First, using an editor of your choice, create a new file called testing.js and add the following code:

const assert = require('assert');

function add(n1, n2) {
return 0;
}

First, we import the assert module to use its equal function. The equal function expects three parameters:

  • The current value or expression to be analyzed
  • The expected value
  • The message that should be thrown in case the current and expected value are not equal

If the assertion fails, the program will be finished and you will see the reason why the assertion fails in your Terminal.

Once we import our assert module, we proceed to create our add function. However, this function does not perform any operation; this is because our intention is to first write the test and make it fail, and after that we will implement the logic itself in the next point. In the same testing.js file, append to the following code with the testing case right below the add function:

let result = add(5, 5);
assert.equal( result, 10, "Should be 10");

console.log("Test passed!!");

Now we have our test case, which will compare the current value—add(5, 5)housed into the result variable against the expected value10, and if they are not equal, the Should be 10 error message will be displayed and as the program is complete, the next expressionconsole.log—won't be executed.

It's time to execute our test. Using your Terminal, get into your folder where you have created the testing.js file and execute the following command:

$ node testing.js

If everything went wrong, you should see the following output:

assert.js:81
throw new assert.AssertionError({
^
AssertionError: Should be 10
...

Cool! Now it's time to implement the code and pass our test.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset