Exercise Solutions: Unit Testing

Automatic Testing to Find Errors

  1. Get the sourcecode file and the test code file to talk to each other.

    1. Add two require statements.

      checkFive.spec.js:

      1const test = require('../checkFive.js');
      2const assert = require('assert');
      

    Back to the exercises

  1. Check that checkFive produces the correct output when passed a number less than 5.

    1. Write a descriptive test name.

      checkFive.spec.js:

      1it("returns 'num is less than 5' when num < 5.", function(){
      2   // test code //
      3});
      
    1. Use assert.

      checkFive.spec.js:

      assert.strictEqual(output, "2 is less than 5.");
      
    1. Change the sourcecode file and see that the test fails.

      checkFive.js:

      1if (num > 5) {
      2   // sourcecode //
      3}
      

    Back to the exercises

Try One on Your Own

  1. Set up the RPS.js and RPS.spec.js files to talk to each other.

    RPS.js:

    1module.exports = {
    2      whoWon: whoWon
    3};
    

    RPS.spec.js:

    1const test = require('../RPS.js');
    2const assert = require('assert');
    

    Back to the exercises

  1. Two sample tests.

    RPS.spec.js:

     1describe("whoWon", function(){
     2
     3   it("returns 'Player 2 wins!' if P1 = rock & P2 = paper", function(){
     4      let output = test.whoWon('rock','paper');
     5      assert.strictEqual(output, "Player 2 wins!");
     6   });
     7
     8   it("returns 'Player 2 wins!' if P1 = paper & P2 = scissors", function(){
     9      let output = test.whoWon('paper','scissors');
    10      assert.strictEqual(output, "Player 2 wins!");
    11   });
    12
    13   // other test cases //
    14
    15}
    

Typo to fix:

In RPS.js, there is a conditional block that checks if player1 plays 'scissors' and player2 plays 'rock '. The 'rock ' string contains a trailing space that should be removed.

Back to the exercises