简体   繁体   中英

While doing Unit testing with Jasmine should I mock or spy or stub my service which is injected in my component?

In my component.ts the service has been injected in the constructor of the component which subscribe to a function in the service and receives information. How can I test my component in that case?

In the component.ts I have the following code :-

How can I proceed in that case?

You'll either have to mock your service, which is always a good idea when it comes to unit testing, or use a spy as explained below.

Option Mock:

...
providers: [
 {provide: PartService, useClass: MockPartService},
],
...

class MockPartService {
   list(): Observable<Part[]> {
   return Observable.of([...]);
}

You'll have to write MockService with an identical method signature a the one you're calling within your test. You may want to hardcode your expected return value into this MockClass. This is usually what you want when you want to mock eg API requests etc. so your test doesn't throw.

Option Spy:

const mockParts: Part[] = [...]
const serviceSpy = spyOn(PartService, 'list').and.ReturnValue(Observable.of(mockParts));

Use this when you expect a specific return by your service for your test.

You're also free to mix both within your tests. A stub spyOn(YourService, 'YourMethod').and.stub() will just prevent the actual method from being called but will not return any value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM