AUTOMATE AND ORGANIZE TESTS
Review
You can now write tests with Mocha and Node’s assert.ok() ! In this lesson you learned to:
Install Mocha with npm
Organize tests with describe() and it()
Ensure your tests are isolated and expressive with the four phases of a test
Ensure your tests are reliable with hooks
Write assertions with assert.ok()
As you continue to write tests, remember to always evaluate them against the characteristics of a good test: fast, complete, reliable, isolated, maintainable, and expressive. If you are meeting these six criteria, you are creating high quality test frameworks!
const assert = require('assert');
const fs = require('fs');
describe('appendFileSync', () => {
const path = './message.txt';
afterEach(() => {
// Teardown: delete path
fs.unlinkSync(path);
})
it('writes a string to text file at given path name', () => {
// Setup
const str = 'Hello Node.js';
// Exercise: write to file
fs.appendFileSync(path, str);
// Verify: compare file contents to string
const contents = fs.readFileSync(path);
assert.ok(contents.toString() === str);
});
});
console.log = function() {};
const assert = require('chai').assert;
const fs = require('fs');
const Structured = require('structured');
const code = fs.readFileSync('./test/index_test.js', 'utf8');
describe('Checkpoint 4', () => {
it('asserts that hook contains teardown', () => {
let structure1 = function() {
describe(_, () => {
afterEach( () => {
fs.unlinkSync($path);
});
});
};
let structure2 = function() {
describe(_, () => {
afterEach( function() {
fs.unlinkSync($path);
});
});
};
let varCallbacks = {
'$path': function(path) {
if (path.name !== 'path') {
return {failure: "`fs.unlinkSync()` missing argument `'path'`"};
}
return true;
}
};
// assert that structure matches
let isMatch1 = Structured.match(code, structure1, {varCallbacks: varCallbacks});
let isMatch2 = Structured.match(code, structure2, {varCallbacks: varCallbacks});
let failureMessage = 'Structure is not correct or hook is missing `fs.unlinkSync()`';
assert.isOk(isMatch1 || isMatch2, varCallbacks.failure || failureMessage);
});
});
{
"name": "learn-mocha-intro-start",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha test/**/*_test.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"mocha": "^3.5.3"
}
}