UNPKG

2.56 kBtext/coffeescriptView Raw
1expect = require('chai').expect
2
3Binder = require('binder')
4Injector = require('injector')
5
6
7class Parent
8 name: 'Parent'
9
10class Child1 extends Parent
11 name: 'Child1'
12
13class Child2 extends Parent
14 name: 'Child2'
15
16class GrandChild extends Child1
17 name: 'GrandChild'
18
19class MySingleton
20 @scope: 'SINGLETON'
21
22class MyParamed
23 constructor: (@name, @age) ->
24
25describe 'An injector', ->
26 it 'should create an instance', ->
27 injector = new Injector()
28
29 instance = injector.getInstance(GrandChild)
30 expect(instance.name).to.equal 'GrandChild'
31
32 instance = injector.getInstance(Parent)
33 expect(instance.name).to.equal 'Parent'
34
35 it 'should bail when trying to create an unknown child', ->
36 injector = new Injector()
37 create = -> injector.getInstance(666)
38 expect(create).to.throw /Could not resolve/
39
40 it 'should return the same instance when creating a singleton', ->
41 injector = new Injector()
42 inst1 = injector.getInstance(MySingleton)
43 inst2 = injector.getInstance(MySingleton)
44
45 expect(inst1).to.equal inst2
46
47 it 'should pass constructor args', ->
48 injector = new Injector()
49
50 unnamed = injector.getInstance(MyParamed)
51 named = injector.getInstance(MyParamed, 'Frank', 44)
52
53 expect(unnamed.name).to.not.exist
54 expect(unnamed.age).to.not.exist
55 expect(named.name).to.equal 'Frank'
56 expect(named.age).to.equal 44
57
58 it 'should obey a simple singleton binding', ->
59 class MyBinder extends Binder
60 configure: ->
61 @bind(Parent).to(Child2)
62
63 injector = new Injector(new MyBinder())
64
65 expect(injector.getInstance(Child2)).to.be.an.instanceOf Child2
66 expect(injector.getInstance(Parent)).to.be.an.instanceOf Child2
67
68 it 'should obey a simple instance binding', ->
69 class MyBinder extends Binder
70 configure: ->
71 @bind(Child2).to(GrandChild).inScope('INSTANCE')
72
73 injector = new Injector(new MyBinder())
74 inst1 = injector.getInstance(Child2)
75 inst2 = injector.getInstance(Child2)
76
77 expect(inst1).to.be.an.instanceOf GrandChild
78 expect(inst2).to.be.an.instanceOf GrandChild
79
80 expect(inst1).to.not.equal inst2
81
82 it 'should obey a simple constant binding', ->
83 class MyBinder extends Binder
84 configure: ->
85 @bindConstant('pants').to(666)
86 injector = new Injector(new MyBinder())
87 expect(injector.getInstance('pants')).to.equal 666
88
89 it 'should return itself when asking for an injector', ->
90 injector = new Injector()
91 injector.someNewField = 3
92 expect(injector.getInstance(Injector).someNewField).to.equal 3