Exercise Solutions: Unit Testing¶
Automatic Testing to Find Errors¶
Get the sourcecode file and the test code file to talk to each other.
Add two
require
statements.checkFive.spec.js
:1
const test = require('../checkFive.js');
Check that
checkFive
produces the correct output when passed a number less than 5.Write a descriptive test name.
checkFive.spec.js
:1 2 3
it("returns 'num is less than 5' when num < 5.", function(){ // test code // });
Use
expect
.checkFive.spec.js
:expect(output).toEqual("2 is less than 5.");
Change the sourcecode file and see that the test fails.
checkFive.js
:1 2 3
if (num > 5) { // sourcecode // }
Try One on Your Own¶
Set up the
RPS.js
andRPS.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');
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.