vv-di
Version:
Simple IoC Container
96 lines (79 loc) • 2.99 kB
JavaScript
var chai = require('chai');
var mocha = require('mocha');
var describe = mocha.describe;
var it = mocha.it;
var expect = chai.expect;
chai.use(require('chai-as-promised'));
var Container = require('./../container');
describe('container', function () {
describe('can register and make a dependency instance', function () {
var container = new Container();
container.bind('foo', function () {
return 'bar';
});
it('should perform correctly', function () {
expect(container.make('foo')).to.be.equals('bar');
})
});
describe('can resolve dependencies recursively', function () {
var container = new Container();
var BarClass = function () {
this.id = 'Bar';
};
var FooClass = function (bar) {
this.bar = bar;
this.id = 'Foo';
};
container.bind('Bar', function () {
return new BarClass();
});
container.bind('Foo', function (container) {
return new FooClass(container.make('Bar'));
});
it('should resolve bar when resolve foo', function () {
var foo = container.make('Foo');
expect(foo.id).to.be.equals('Foo');
expect(foo.bar.id).to.be.equals('Bar');
});
});
describe('can register a singleton instance and cache it for the next time of resolvation', function () {
var container = new Container();
var Foo = function () {
this.unique = Math.random();
};
container.singleton('foo', function () {
return new Foo();
});
it('should resolves same instance', function () {
var instance1 = container.make('foo');
var instance2 = container.make('foo');
expect(instance1.unique).to.be.equals(instance2.unique);
})
});
describe('can get it\'s singleton', function () {
var c1 = Container.instance();
var c2 = Container.instance();
it ('should get the same instance', function () {
expect(c1).to.be.deep.equals(c2);
})
});
describe('can resolve async service', function () {
var container = new Container();
container.bindAsync('async1', function (container, call) {
setTimeout(function () {
call.done('async-service1');
}, 1)
});
container.bindAsync('async2', function (container, call) {
setTimeout(function () {
call.done('async-service2');
}, 2)
});
it ('should be booted correctly and can resolve correct services', function () {
var bootPromise = container.boot();
return expect(bootPromise).to.eventually.equals(container).then(function (bootedContainer) {
expect(bootedContainer.make('async1')).to.be.equals('async-service1');
});
});
})
});