2017-04-20 96 views
6

我正在使用Http依賴關係測試服務。每個測試看起來是這樣的:Angular2服務測試:使用beforeEach注入依賴關係

import { TestBed, async, inject } from '@angular/core/testing'; 
import { ValidationService } from './validation.service'; 
import { HttpModule, Http, Response, ResponseOptions, RequestOptions, Headers, XHRBackend } from '@angular/http'; 
import { MockBackend, MockConnection } from '@angular/http/testing'; 

describe('DashboardService',() => { 
    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     imports: [HttpModule], 
     providers: [ 
     ValidationService, 
     { provide: XHRBackend, useClass: MockBackend } 
     ] 
    }); 
    }); 

    it('should ...', 
    inject([ValidationService, XHRBackend], 
     (service: ValidationService, mockBackEnd: MockBackend) => { 
     mockBackEnd.connections.subscribe((connection: MockConnection) => { 
      connection.mockRespond(new Response(new ResponseOptions({ 
      body: JSON.stringify('content') 
      }))); 
     }); 
     })); 
     // assertions ... 
}); 

正如你所看到的,我需要在每次注入後端模擬。

是否有可能在每次測試之前使用beforeEach注入依賴項?

回答

13

是否有可能在每次測試之前使用beforeEach注入依賴項?

當然可以。

let service; 

beforeEach(inject([Service], (svc) => { 
    service = svc; 
})) 

雖然你也可以只得到了TestBed的服務,這也是一個注射器

let service; 

beforeEach(() => { 
    TestBed.configureTestingModule({ 
    ... 
    }) 

    service = TestBed.get(Service); 
}) 
+0

謝謝你,我會嘗試兩種方式,看看有什麼我最適合。 – trichetriche

+0

有沒有一種方法可以在不使用TestBed設置的情況下注入Service? –