Skip to content

Instantly share code, notes, and snippets.

@cmstead
Last active April 5, 2018 19:56
Show Gist options
  • Save cmstead/205b5b731426fc664687c92835c614ec to your computer and use it in GitHub Desktop.
Save cmstead/205b5b731426fc664687c92835c614ec to your computer and use it in GitHub Desktop.
Test example using Dject
'use strict';
const assert = require('chai').assert;
const sinon = require('sinon');
const container = require('../example-container');
describe('file reader', function () {
let fileReader;
let logSpy;
beforeEach(function () {
// Building test doubles for node internals becomes trivial
const fsFake = {
readFileSync: () => throw new Error('The error is coming from inside the test!')
};
logSpy = sinon.spy();
const loggerFake = {
log: logSpy
};
// Create a child container to isolate the tests from your main container so you don't contaminate other tests.
const childContainer = container.new();
// This gives us direct line-of-sight into what our test doubles will be doing
// Since there is no filesystem or module caching, moving dependencies won't
// impact our test isolation
childContainer.register(() => fsFake, 'fs');
childContainer.register(() => loggerFake, 'logger');
// Note, this file can be moved without impacting the tests.
fileReader = childContainer.build('fileReader');
});
describe('readAFile', function () {
it('logs an error when the filesystem cannot read a file', function () {
fileReader.readAFile('./some/test/file.txt');
assert.equal(logSpy.getCall(0)[0], 'The error is coming from inside the test!');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment