Угловой модульный тест: Как выполнить модульный тест .map ()? - PullRequest
2 голосов
/ 19 июня 2019

Мне нужно протестировать метод одного из сервисов, и я не уверен, как достичь 100% покрытия кода для частей кода, которые выполняются в результате вызова какого-либо внедренного метода сервиса.

СервисМетод тестирования:

@Injectable()
export class BomRevisiosnsService {
  constructor(
    private baseService: BaseService,
    private appConstants: AppConstants,
    private dmConstants: DMConstants
  ) { }

  public getRevisionsData(): any {
    var itemId = this.appConstants.userPreferences.modelData['basicDetails']['itemId'];
    let url = this.dmConstants.URLs.GETBOMREVISIONS + itemId + "/GetRevisionsAsync";
    let headers = {
      "Content-Type": "application/json",
      UserExecutionContext: JSON.stringify(this.appConstants.userPreferences.UserBasicDetails),
    }
    if (itemId != null || itemId != undefined) {
      return this.baseService.getData(url, headers)
        .map(response => {
          // this area not getting covered.
          return response;
        });
    }
  }
}

Как покрыть:

.map(response => {
  return response;
});

В следующем:

Тест:

it('should return response if itemId is not null or undefined', () => {
  let mockData = [1,2,3];
  let mockObservable = Observable.of(mockData);
  spyOn(baseService, 'getData').and.returnValue(mockObservable);
  appConstants.userPreferences.modelData['basicDetails']['itemId']=4; // itemId not null or undefined
  dMConstants.URLs.GETBOMREVISIONS ="dummy url";
  subject.getRevisionsData();
  expect(baseService.getData).toBe(mockData); // How do I test .map()?
});

1 Ответ

0 голосов
/ 19 июня 2019
it('should return response if itemId is not null or undefined', () => {
  ...
  const spy = spyOn(baseService.getData).and.return(mockedData)// you need to define data returned by baseService.getData
  const result = subject.getRevisionsData();
  expect(spy).toHaveBeenCalled(); // How do I test .map()?
  expect(result).toEqual(mockedData);// for simple map it will be the same thing that is returned for more complicated map it may differ
});
...