【问题标题】:Unable to validate a structure of JSON in a unit test and also the result doesn't match the expected outcome无法在单元测试中验证 JSON 的结构,并且结果与预期结果不匹配
【发布时间】:2020-07-31 19:10:46
【问题描述】:

我正在尝试为收到http.post 的响应时调用的函数运行unit test

  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 检查响应的结构是否正常。它应该有resultadditional-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);

});

如果我在validateServerResponseStructure 上没有spy,那么我的测试用例将失败,因为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

我做错了什么?

【问题讨论】:

    标签: angular6 karma-jasmine angular-test


    【解决方案1】:

    有趣的是,如果我将单元测试中 httpResponse 中的 type &lt;T&gt; 更改为 Object 而不是 string,则代码可以工作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2021-03-23
      相关资源
      最近更新 更多