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:

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

    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:

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

      checkFive.spec.js:

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

      checkFive.js:

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

    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:

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

    RPS.spec.js:

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

    Back to the exercises

  1. Two sample tests.

    RPS.spec.js:

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

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