2016-03-25 198 views
0

我試着寫一些單元測試像一個服務:angular2單元測試

export class Service1 { 
... 
    public constructor(service2: Service2, service3: Service3) {} 
... 
} 

其中服務2包含反過來,服務3:

export class Service2 { 
... 
    public constructor(service3: Service3, stringa: string) {} 
... 
} 

我開始測試 在真正可怕的方式,如:

it("check XXX",() => { 
    let service3: Service3= new Service3(); 
    let service2: service2= new service2(service3, "stringa"); 
    let service1: Service1 = new Service1(service2, service3); 
    expect(X).toEqual(X); 
}); 

,但現在,我使用beforeEachProviders什麼HAPP恩與此:

beforeEachProviders(() => { 
    return [ 
     provide(Service2, { useclass: MockService2}), 
     provide(Service3, { useclass: MockService3}), 
     provide('stringa', { useValue: "stringa"}), 
     Service1 
    ]; 
    }); 

    it('check XXX ', inject(
    [Service2, Service3], (service2: Service2, service3: Service3) => { 
    expect(true).toEqual(true); 
    })); 

是:

Failed: No provider for String! (Service2-> String). 

能someboby幫助我嗎?

在此先感謝。

回答

0

如果你想從注入依賴注入的字符串值,你需要使用@Inject裝飾:

export class Service2 { 
    ... 
    public constructor(service3: Service3, @Inject('stringa') stringa: string) {} 
    ... 
} 

由於事實上,注射默認依賴於參數類型,如果你不使用裝飾者@Inject

+0

我已經在構造函數中使用了@Inject裝飾器,但不是在模擬服務中!真的非常感謝你! – AntuJitsu