2017-04-01 48 views
0

是否可以在相同的上下文中使用ReflectiveInjector更改提供商?我需要B在第二個測試中使用不同的值。一個& B是服務...在使用ReflectiveInjector的測試中更改提供商

let injector: ReflectiveInjector; 
    beforeEach(() => { 
    injector = ReflectiveInjector.resolveAndCreate([ 
     A, { provide: B, useValue: null } 
    ]); 
    }); 

    ... 

    it('should be null',() => { 
    const a = injector.get(A); 
    expect(a.B).toBe(null) 
    }); 

    it('shoul NOT be null',() => { 
    const a = injector.get(A); 
    // need something like this: 
    // a.B = injector.CHANGE_B_PLEASE({ provide: B, useValue: true }) 
    expect(a.B).not.toBe(null) 
    }); 
+0

@GünterZöchbauer在過去6個月中有些事情發生了變化,或者事情與[之前](http://stackoverflow.com/a/40035615/1876949)相同嗎?看起來我再次遇到同樣的問題(; – Sasxa

+0

你可以創建基於http://stackoverflow.com/questions/40032954/how-to-change-ngmodule-configuration-at-runtime的重新啓動?代碼在這裏和在前面的問題是完全不同的,你只能創建新的注入器,你可以指定父注入器 – yurzui

+0

@yurzui代碼是不同的,但想法是一樣的 - 用另一個替換一個提供者對於我做'setup(value)=> {/*做什麼beforeEach did * /}';我只是想知道是否有更好的方法來使用'ReflectiveInjector'。 – Sasxa

回答

0

我的測試解決方案:

let injector: ReflectiveInjector; 
    setup((value) => { 
    injector = ReflectiveInjector.resolveAndCreate([ 
     A, { provide: B, useValue: value } 
    ]); 
    }); 

    ... 

    it('should be null',() => { 
    setup(null); 
    const a = injector.get(A); 
    expect(a.B).toBe(null) 
    }); 

    it('shoul NOT be null',() => { 
    setup(true); 
    const a = injector.get(A); 
    const b = injector.get(B); 
    expect(a.B).toBe(true) 
    expect(b).toBe(true) 
    }); 

欲瞭解更多信息檢查: