angular httpClientTestingModule httpMock giving error: found 2 requests

谁都会走 提交于 2019-12-04 20:31:28

I'm sorry if my answer is not as complete as the previous one, but I am on phone. If you need more explanation, notify me on Monday, il will have a computer to help you.

I can see here that you're testing a component.

In unit testing, you are supposed to test the feature you're on. Since the http calls are made by your service, you should test if they are correct in the tests of your service, not in your component.

This means that in your component, you only test if the correct method of your service is called. This is done by using jasmine spies.

This also means that you can mock your service. If you mock your service, you won't have to mock its dependencies, because you will provide a simple object that has no dependency.

To mock a service, you will need to provide all the properties you are using in your component to your mock. From what I see, you only use getComments, so let's mock :

const serviceMock = {
  provide: YourServiceName, 
  useValue: {
    getComments: () => Observable.of(null)
  }  
};

This is the format of a mock. It must respect some conditions :

  • as said previously, it must contain all of the properties used.
  • those properties must have the same signature. Here, getComments is a function that returns an observable of comments (null is every type), just like in your service.

Now, you can put this mock into your test bed :

providers: [serviceMock]

The logic to get the service instance is the same I explained in your previous question.

Now, you can write a test that checks if the component is calling the service correctly ! You just have to make a spy, call your component function, and expect.

spyOn(serviceInstance, 'getComments').and.callThrough(); // use returnValue(Observable.of(commentsMock)) instead of callThrough() if you want to test your logic made on the value returned by the function
component.functionCall();
expect(serviceInstance.getComments).toHaveBeenCalled();

And voilà !

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