diff --git a/lib/index.js b/lib/index.js index 5107c8b..3c23d8a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -12,4 +12,6 @@ exports.fs = exports.dir = require('./sources/dir'); exports.node = deprecate.function(exports.dir, 'Container#node: Use Container#dir instead'); +exports.singleton = require('./sources/singleton'); + exports.node_modules = require('./sources/node_modules'); diff --git a/lib/sources/singleton.js b/lib/sources/singleton.js new file mode 100644 index 0000000..389c59f --- /dev/null +++ b/lib/sources/singleton.js @@ -0,0 +1,25 @@ +/** + * Sources objects from a js singleton. + * + * This source allows to inject manually singletons as dependencies + * + * This typically allows to override specific modules for testing purposes + * + * Examples: + * + * IoC.use(IoC.singleton('settings', {foo : 'bar'})); + * + * @param {string} id - the name of the component + * @param {any} sglt - the singleton that is injected + * @return {function} + * @public + */ +module.exports = function(id, sglt) { + return function app(idLocal){ + if (idLocal === id) { + const singleton = Promise.resolve(sglt); + singleton['@singleton'] = true; + return singleton; + } + } +}; diff --git a/test/sources/singleton.test.js b/test/sources/singleton.test.js new file mode 100644 index 0000000..97fbf17 --- /dev/null +++ b/test/sources/singleton.test.js @@ -0,0 +1,31 @@ +var singleton = require('../../lib/sources/singleton'); + +describe('source/singleton', function() { + var sglt = {foo: 'bar'}; + var source = singleton('settings', sglt) + + var obj = source('settings') + + it('should return @singleton component', function() { + expect(obj['@singleton']).to.be.equal(true); + }); + + it('should return undefined if module not found', function() { + var obj = source('fubar'); + expect(obj).to.be.undefined; + }); + + let resolved; + + before(function(done) { + obj.then(function(o) { + resolved = o; + done(); + }, done); + }); + + it('should be resolved with settings', function() { + expect(resolved).to.be.equal(sglt); + }); + +});