Подтвердить что ты не робот

Angular2 - http-код покрытия кода

Мои компоненты .ts есть,

 getHomePageData() : void{
    this.homeservice.getHomePageData()
          .subscribe(
              data =>   {

                            //console.log("response status ################### "+data.status);
                            //console.log("getUserData response ************ \n"+JSON.stringify(data));
                            this.defaultFacilityId = data.response.defaultFacilityId;
                            this.defaultFacilityName = data.response.defaultFacilityName;
                            this.enterpriseId = data.response.enterpriseId;
                            this.enterpriseName = data.response.enterpriseName;
                            this.facilityList = data.response.facilityList;
                            this.userName = data.response.userName;

                            this.showDefaultPopoup();
                        },
              error =>  {
                            console.error(error);
                            //this.errorMessage="Technical error - Contact Support team !" ;
                        }
          );

  }

Итак, my component.spec.ts есть,

 it('getHomePageData with SUCCESS - getHomePageData()', () => {
    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));

    });

     backend.connections.subscribe((data) => {
      //expect(data.response.facilityId).toEqual("55303.0");
      //expect(subject.handleError).toHaveBeenCalled();
    })

    service.getHomePageData().subscribe((data) => {
          //expect(videos.length).toBe(4);
          expect(data.response.defaultFacilityId).toEqual("55303.0");
          component.defaultFacilityId = data.response.defaultFacilityId;
          component.defaultFacilityName = data.response.defaultFacilityName;
          component.enterpriseId = data.response.enterpriseId;
          component.enterpriseName = data.response.enterpriseName;
          component.userName = data.response.userName;
          console.log("$$$$$$$$$$$$$$$$**********$$$$$$$$$$$$$$$$$$$$$");
      });

  });

Когда я пытаюсь запустить тестовый пример. Он прошел. Но пока я смотрю на покрытие кода, он не охватывает код, показанный красным цветом ниже ввести описание изображения здесь

Пожалуйста, помогите получить полный охват кода. Спасибо.

4b9b3361

Ответ 1

В тесте, который вы показали здесь, вы, кажется, не вызываете getHomePageData() из своего компонента

Попробуйте создать свой тест следующим образом:

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 properties now
  expect(component.defaultFacilityId).toEqual("55303.0");

});

FakeAsync позволяет писать тесты в более линейном стиле, поэтому вам больше не нужно подписываться на функцию сервиса, чтобы писать ваши ожидания.

В тесте FakeAsync вы можете вызвать tick() после вызова, где выполняется асинхронная операция, чтобы моделировать проход времени, а затем продолжить поток вашего кода.

Подробнее об этом можно прочитать здесь: https://angular.io/docs/ts/latest/testing/#!#fake-async

EDIT - Случай ошибок

Чтобы проверить логику ошибок, вы можете вызвать mockError или настроить ответ об ошибке с помощью mockRespond в вашем соединении:

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');
});

Что мы делаем внутри подписки, убедитесь, что в любое время, когда конечная точка GetUserData вызывается внутри этого метода тестирования, она вернет ошибку.

Поскольку мы проверяем ошибки и успехи отдельно в тесте успеха, нет необходимости добавлять связанные с ошибкой настройки в параметры запроса.

Ответ 2

Используете ли вы данные JSON? Тогда вы, вероятно, должны использовать map() перед использованием .subscribe().

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

Попробуйте организовать свой код следующим образом:

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')
  );
}

Надеюсь, что это поможет,

Приветствия