Angular2 - http call Code coverage

时光毁灭记忆、已成空白 提交于 2019-12-05 01:04:30

In the test you've shown here you don't seem to be calling getHomePageData() from your component

Try building your test like this:

import { fakeAsync, tick } from '@angular/core/testing';
...
it('getHomePageData with SUCCESS - getHomePageData()', fakeAsync(() => {
  backend.connections.subscribe((connection: MockConnection) => {
  //expect(connection.request.url).toEqual('http://localhost:8080/MSMTestWebApp/UDM/UdmService/Home/');
  expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData');

  expect(connection.request.method).toEqual(RequestMethod.Get);
  expect(connection.request.headers.get('Content-Type')).toEqual('application/json');
  let options = new ResponseOptions({
    body:
    {
      "request": { "url": "/getUserData" },
      "response": {
             "defaultFacilityName":"3M Health Information Systems",
              "enterpriseId":"11.0",
              "enterpriseName":"HSA Enterprise",
              "defaultFacilityId": "55303.0",
              "userName":"Anand"
      },
      "error": ""
    },
    status : 200
  });

  connection.mockRespond(new Response(options));

  });

  // If this function is not automatically called in the component initialisation
  component.getHomePageData();
  tick();
  //you can call expects on your component's properties now
  expect(component.defaultFacilityId).toEqual("55303.0");

});

FakeAsync allows you to write tests in a more linear style so you no longer have to subscribe to the service function to write your expectations.

In a FakeAsync test function you can call tick() after a call where an asynchronous operation takes place to simulate a passage of time and then continue with the flow of your code.

You can read more about this here: https://angular.io/docs/ts/latest/testing/#!#fake-async

EDIT - Error Case

To test the error logic you can call mockError or set up an error response using mockRespond on your connection:

it('getHomePageData with ERROR- getHomePageData()', fakeAsync(() => {
  backend.connections.subscribe((connection: MockConnection) => {
    if (connection.request.url === 'http://192.168.61.158:9080/GetUserData') {
        // mockError option
        connection.mockError(new Error('Some error'));
        // mockRespond option
        connection.mockRespond(new Response(new ResponseOptions({
          status: 404,
          statusText: 'URL not Found',
        })));
    }

  component.getHomePageData();
  tick();
  //you can call expects now
  expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData');
  expect(connection.request.method).toEqual(RequestMethod.Get);
  expect(connection.request.headers.get('Content-Type')).toEqual('application/json');
  expect('you can test your error logic here');
});

What we're doing inside the subscription is making sure that anytime the GetUserData endpoint is called within this test method it will return an error.

Because we test errors and successes separately in the success test there's no need to add the error related settings in the request options.

Are you using JSON data? Then you should probably use map() before using .subscribe().

.map((res:Response) => res.json())

Try organizing your code like this:

ngOnInit() {
this.getHomePageData();
}

getHomePageData() {
 this.http.get('your.json')
  .map((res:Response) => res.json())
  .subscribe(
    data => { 
      this.YourData = data
    },
    err => console.error(err),
    () => console.log('ok')
  );
}

Hope it helps,

Cheers

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