Skip to content

Latest commit

 

History

History
65 lines (57 loc) · 2.71 KB

02 - Your first unit test.md

File metadata and controls

65 lines (57 loc) · 2.71 KB

Practical 2 - Your first unit test

Objectives

  • Get access to your production code & test libraries within your test code
  • Use describe and it blocks to create a test fixture
  • Write a basic test which enforces a happy-case scenario
  • Run the test suite with a green result

Extensions

  • Write tests for other happy-case scenarios, and refactor the test code if necessary
  • Write edge-cases for unexpected input
  • Write a test and then production code to handle invalid inputs
  • Refactor the production code using tests as a safety-net

Set-up Steps

  1. Commit any outstanding changes on your Prac01 branch: git commit -am 'Some message'
  2. Head back over to master: git checkout master
  3. Check out the Start Point for Prac 2: git checkout Prac02-StartPoint
    • This references a defined tag in the repository, you must use exactly this name
  4. Create a branch to make your changes on without impacting the main repo: git checkout -b Prac02
    • This branch is your own working space, you can call it anything you want

Practical Steps

  1. Use node's require to get access to the NameToNumberService for your test code
  2. Also get acces to Chai to perform assertions
  3. Add a top-level describe block to describe the thing we're testing
  4. Add a second-level describe block to describe the scenario we're testing
  5. Add an it block to create your first test case
  6. Inside the it block, write code to set up test data and call the service
  7. Add an assertion to actually verify the result
  8. Run the test and see a green result

Solutions

Here's a step-by-step walkthrough of the practical steps, for if you get stuck :)

  1. Use node's require to get access to the NameToNumberService for your test code
    • var nameToNumberService = require('../src/name-to-number-service');
  2. Also get acces to Chai to perform assertions
    • var chai = require('chai');
  3. Add a top-level describe block to describe the thing we're testing
    • describe('NameToNumber Service', function() { ... });
  4. Add a second-level describe block to describe the scenario we're testing
    • describe('with 4 buckets', function() { ... });
  5. Add an it block to create your first test case
    • it('should put Alice in the first', function() { ... });
  6. Inside the it block, write code to set up test data and call the service
    var inputName = "Alice";
    var buckets = 4;
    var expectedBucket = 1;
    
    var actualBucket = nameToNumberService.generateNumber(inputName, buckets);
  7. Add an assertion to actually verify the result
    • actualBucket.should.equal(expectedBucket);
  8. Run the test and see a green result
    • npm test