Невозможно проверить структуру JSON в модульном тесте, а также результат не соответствует ожидаемому результату - PullRequest
0 голосов
/ 18 апреля 2020

Я пытаюсь запустить unit test для функции, которая вызывается при получении ответа http.post.

  handleSuccessResponseForUserProfileRequest(res: HttpSentEvent|HttpHeaderResponse|HttpResponse<any>|HttpProgressEvent|HttpUserEvent<any>) {
    const ev = <HttpEvent<any>>(res);
    if (ev.type === HttpEventType.Response) {
      console.log('response from server: body ',ev.body);
      const isResponseStructureOK: boolean = this.helper.validateServerResponseStructure(ev.body);
      if (isResponseStructureOK) {
        const response: ServerResponseAPI = ev.body;
        this.userProfileSubject.next(new Result(response.result, response['additional-info']));
      } else {
        this.userProfileSubject.next(new Result('error', 'Invalid response structure from server'));
      }
    } else {
    }
  }

validateServerResponseStructure проверяет, что структура ответа в порядке. Он должен иметь клавиши result и additional-info

validateServerResponseStructure(res: any): boolean {
      const keys = Object.keys(res);
      const isTypeCorrect: boolean = (
        ['result', 'additional-info'].every(key => keys.includes(key))
        && keys.length === 2);
      return isTypeCorrect;

  }

Регистр, который я написал, будет

fit('should return if user information isn\'t stored', () => {
  const body = JSON.stringify({"result":"success", "additional-info":"some additional info"});
  const receivedHttpEvent = new HttpResponse({body:body});
  const userService: UserManagementService = TestBed.get(UserManagementService);
  const helperService:HelperService = TestBed.get(HelperService);
  spyOn(userService['userProfileSubject'],'next');
  //spyOn(helperService,'validateServerResponseStructure').and.returnValue(true);
  userService.handleSuccessResponseForUserProfileRequest(receivedHttpEvent);
  const expectedResult = new Result('success', 'some additional info');
  expect(userService['userProfileSubject'].next).toHaveBeenCalledWith(expectedResult);

});

Если я не spy на validateServerResponseStructure, тогда мой Сбой теста, потому что validateServerResponseStructure не удается, хотя мне кажется, что структура в порядке.

Expected spy next to have been called with [ Result({ result: 'success', additionalInfo: 'some additional info' }) ] but actual calls were [ Result({ result: 'error', additionalInfo: 'Invalid response structure from server' }) ].

Если я шпионю за validateServerResponseStructure и возвращаю true, тогда я получаю ошибку

Expected spy next to have been called with [ Result({ result: 'success', additionalInfo: 'some additional info' }) ] but actual calls were [ Result({ result: undefined, additionalInfo: undefined }) ].

Интересно, что если я добавлю следующие два отпечатка, то они покажут разные значения !!

console.log('extracted response ',response);
        console.log('sending response '+response.result + 'and additional info' +response['additional-info']);

Я вижу

extracted response  {"result":"success","additional-info":"some additional info"}
sending response undefined and additional info undefined

Что я делаю не так?

1 Ответ

0 голосов
/ 18 апреля 2020

Интересно, что код работает, если я изменю type <T> в httpResponse в модульном тесте на Object вместо string.

const body = {"result":"success", "additional-info":"some additional info"};
      const receivedHttpEvent = new HttpResponse({body:body});
...