JS UNIT TESTING
/////////////////////////////////////////////////////////
PART 1: JS Unit Testing
/****
*
****/*
Test suite
// in the console
mocha <test_name.js>
For debugging... creating a test folder. For the example used:
test > utilities_spec.js // this relates to the utilities.js file
Mocha makes:
/****
*
****/*
Unit Tests: Writing tests that confirm an individual function or piece of code as working how we want it to. Unit tests are like drills.
Integration Testing: Used to test new code added to pre-existing code and that they run correctly together without breaking.
End-To-End Testing: Running the application from start to finish to test everything that we can. Maybe only a few times run in a product cycle.
/****
*
****/*
BDD is an approach to building software.
Refactoring:
/****
*
****/*
Testing for title case
npm install chai --save-dev touch textUtilites.js
// in textUtitlies.js
var expect = require('chai').expect;
expect(true).to.be.true;
function titleCase(title) { return title; }
expect(titleCase('the great mouse detective')).to.be.a('string');
/****
*
****/*
// in textUtitlies.js
var expect = require('chai').expect;
expect(true).to.be.true;
function titleCase(title) { var words = title.split(' '); var titleCasedWords = words.map(function(word) { return word[0].toUpperCase() + title.substring(1); });
return titleCasedWords.join(' ');
}
expect(titleCase('the great mouse detective')).to.be.a('string'); expect(titleCase('a')).to.equal('A'); expect(titleCase('vertigo')).to.equal('Vertigo'); expect(titleCase('the great mouse detective')).to.equal('The Great Mouse Detective');
/////////////////////////////////////////////////////////
PART 2: Getting started with Chai and Mocha
/****
*
****/*
/////////////////////////////////////////////////////////
PART 4: Going further
mocha --reporter min mocha --reporter markdown // for git
Check the websites.
Feel free to add it to your package.json file.
/****
*
****/*
Communicating test ideas before writing it.
// gametest.js
var expect = require('chai').expect;
describe('GAME INSTANCE FUNCTIONS', function(){ describe('checkGameStatus', function() { it('should tell me when the game is over'); // no expectations yet. It is pending! }); });
Could also add an x... (in this eg, two pending)
xdescribe('GAME INSTANCE FUNCTIONS', function(){ describe('checkGameStatus', function() { it('should tell me when the game is over'); // no expectations yet. It is pending! }); });
/****
*
****/*
How to run auto run tests:
mocha --watch ./test/game_test.js ./game_logic/game_instance.js
// in package.json > scripts
"test:watch": "mocha --watch ./test ./"
npm run test:watch
You can even add other test:watch:name scripts to watch specific things at specific times!
/****
*
****/*
Advanced Features
Writing your own functions in the beforeEach() spec.
sinon.js is also a great framework for stubbing data.