I’m having problems testing a flatiron cli app with Mocha.
The command-line command I’d like to test creates a directory and logs success with app.log.info.
This is the code to be tested (./lib/commands/create.js):
var flatiron = require('flatiron'),
app = flatiron.app,
fs = require('fs'),
path = require('path');
module.exports = function create(name, callback) {
"use strict";
fs.mkdir('./' + name);
app.log.info('Directory created!');
}
This is the test (./test/create.js):
var create = require('../lib/commands/create');
describe('Flatiron command', function () {
"use strict";
describe('#create()', function () {
it('should create a directory ', function () {
create('someDirectory');
// check if the directory was created,
// then remove the directory
});
});
});
mocha test/log -R spec gives me
Flatiron command
#log()
1) should log something
✖ 1 of 1 tests failed:
1) Flatiron command #create() should create a directory :
TypeError: Cannot call method 'info' of undefined
Why is app.lognot available to Mocha?
Is this because of how function logis exported?
Or has this something to do with how flatiron sets up the application? I tried requiring flatiron.app and starting it from the test like this
var create = require('../lib/commands/create'),
flatiron = require('flatiron'),
app = flatiron.app;
describe('Flatiron command', function () {
"use strict";
describe('#create()', function () {
it('should create a directory ', function () {
app.start();
create('someDirectory');
});
});
});
– but with no success, just a different error:
Flatiron command
#create()
1) should create a directory
✖ 1 of 1 tests failed:
1) Flatiron command #create() should create a directory :
TypeError: Object [object Object] has no method 'start'
Or is this a case where you would use spies/stubs/mocks with something like sinon.js to simulate the behavior of app.log somehow? Because I’m not really interested if the logging works, but if the directory is created.
Ok, I’ve got it.
Using
app.start()was not quite it – but it works withapp.init().In flatiron,
app.init()is normally called from within the main file by pluggingflatiron.plugins.cliintoapp.use()like this:Calling
app.init()sets up logging with winston, the flatiron logging plugin.But you can call
app.init()from within the test without callingapp.start()after it.So this works:
Mocha even takes care of the logging:
If you want to stop the logging, you can use
app.log.loggers.default.remove(winston.transports.Console)after you’ve calledapp.init(). You have to require winston to do this.