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

房东的猫 提交于 2020-03-25 18:20:43

问题


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?


回答1:


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 e.g. 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.



来源:https://stackoverflow.com/questions/60506316/while-doing-unit-testing-with-jasmine-should-i-mock-or-spy-or-stub-my-service-wh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!