Angular 2 unit tests: how to override a single provider in TestBed (for unit tests for a service, not for a component, with service dependencies)?

I have:

beforeEach(() => { TestBed.configureTestingModule({ providers: [ DocumentsLoaderSvc, { provide: MgrSvc, useClass: MockMgrSvc }, { provide: URLLoaderSvc, useClass: MockURLLoaderSvcWhenData} ] }); }); 

How to override URLLoaderSvc with a different layout in case of โ€œthisโ€ with its own unique requirement? Is there something like TestBed.overrideProvider ... Right now, I have his every statement in his own "description", with his own beforeEach.

+5
source share
1 answer

Maybe your best bet is simply to customize the layout to fit the needs of different test cases. Save it as an instance and use useValue instead of useClass

 let urlLoderSvc: URLLoaderSvc; beforeEach(() => { urlLoaderSvc = new URLLoaderSvc(); TestBed.configureTestingModule({ providers: [ DocumentsLoaderSvc, { provide: MgrSvc, useClass: MockMgrSvc }, { provide: URLLoaderSvc, useValue: urlLoaderSvc } ] }); }); 

Now in test cases of it you can simply configure an instance of urlLoaderSvc to do whatever you want.

+1
source

Source: https://habr.com/ru/post/1261275/


All Articles