【问题标题】:Unable to get valid assertion involving Jasmine spy on Angular无法在 Angular 上获得涉及 Jasmine 间谍的有效断言
【发布时间】:2019-01-25 12:00:00
【问题描述】:

我正在尝试为仅将 HttpResponse 作为输入并在 HttpResponse 涉及错误时输出 console.error 的服务编写测试。

该服务运行良好,即使在 Karma 填充的浏览器实例中,我也可以看到 console.error,但我编写的断言相同的测试失败。不知道为什么。

这是测试:-

import { TestBed } from "@angular/core/testing";
import { HttpErrorResponse } from "@angular/common/http";
import { GlobalErrorHandler } from "./global-error-handler.service";

describe("GlobalErrorHandler Service", () => {
  let service: GlobalErrorHandler;
  beforeEach(() => {
    service = new GlobalErrorHandler();
  });
  afterEach(() => {
    service = null;
  });

  it("should catch HttpErrors and output to console", () => {
    let error = new HttpErrorResponse({
      url: "Some url",
      error: { message: "error message details" },
      status: 404
    });
    let errorLog = {
      status: error.status,
      message: error.message,
      details: error.error.message
    };
    service.handleError(error);
    console.error = jasmine.createSpy("error");
    expect(console.error).toHaveBeenCalled();
  });
});

这是我正在测试的服务:-

import { Injectable } from "@angular/core";
import { HttpErrorResponse } from "@angular/common/http";

@Injectable({
  providedIn: "root"
})
export class GlobalErrorHandler {
  constructor() {}
  handleError(error: any) {
    if (error instanceof HttpErrorResponse) {
      const errorToShow = {
        status: error.status,
        message: error.message,
        details: error.error.message
      };
      console.error(`Backend returned this error => `, errorToShow);
    } else {
      console.error(`An error occurred => "${error.message}"`);
    }
    // Throwing error...
    throw error;
    // enable the following line to show notification...
    // this.errorNotifier.handleError(error);
  }
}

这是终端上的测试输出:-

ng test
10% building 7/8 modules 1 active ...tarter-app-seven/src sync /\.spec\.ts$/25 01 2019 17:24:12.806:WARN [karma]: No captured browser, open http://localhost:9876/
25 01 2019 17:24:12.817:INFO [karma-server]: Karma v3.1.4 server started at http://0.0.0.0:9876/
25 01 2019 17:24:12.818:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
25 01 2019 17:24:12.830:INFO [launcher]: Starting browser Chrome
25 01 2019 17:24:23.171:WARN [karma]: No captured browser, open http://localhost:9876/    
25 01 2019 17:24:23.405:INFO [Chrome 71.0.3578 (Linux 0.0.0)]: Connected on socket FvdOGo3cHANej7U5AAAA with id 24264291
ERROR: 'Backend returned this error => ', Object{status: 404, message: 'Http failure response for Some url: 404 undefined', details: 'error message details'}
Chrome 71.0.3578 (Linux 0.0.0): Executed 3 of 4 SUCCESS (0 secs / 0.307 secs)
ERROR: 'Backend returned this error => ', Object{status: 404, message: 'Http failure response Chrome 71.0.3578 (Linux 0.0.0) GlobalErrorHandler Service should catch HttpErrors and output to console FAILED
  HttpErrorResponse: Http failure response for Some url: 404 undefined
Chrome 71.0.3578 (Linux 0.0.0): Executed 4 of 4 (1 FAILED) (0 secs / 0.311 secs)
Chrome 71.0.3578 (Linux 0.0.0) GlobalErrorHandler Service should catch HttpErrors and output to console FAILED
Chrome 71.0.3578 (Linux 0.0.0): Executed 4 of 4 (1 FAILED) (0.359 secs / 0.311 secs)
TOTAL: 1 FAILED, 3 SUCCESS
TOTAL: 1 FAILED, 3 SUCCESS

浏览器测试实例截图:-

我希望测试能够通过,尤其是当浏览器实际返回 console.error 时。我是测试和茉莉花的新手。所以这可能是愚蠢的,请帮助我。在此先感谢:)

更新:-

尝试重新排列行以在调用服务之前创建间谍(在 beforeEach 部分中)但得到相同的结果:-

import { TestBed } from "@angular/core/testing";
import { HttpErrorResponse } from "@angular/common/http";
import { GlobalErrorHandler } from "./global-error-handler.service";

describe("GlobalErrorHandler Service", () => {
  let service: GlobalErrorHandler;
  let errorSpy;
  beforeEach(() => {
    service = new GlobalErrorHandler();
    errorSpy = jasmine.createSpy('error');
  });
  afterEach(() => {
    service = null;
  });

  it("should catch HttpErrors and output to console", () => {
    let error = new HttpErrorResponse({
      url: "Some url",
      error: { message: "error message details" },
      status: 404
    });
    let errorLog = {
      status: error.status,
      message: error.message,
      details: error.error.message
    };
    service.handleError(error);
    expect(errorSpy).toHaveBeenCalled();
  });
});

解决方案:-

让它工作,问题是我的方法中有一个 throw 语句,它在到达期望语句之前取消了测试。在这里,我使用了一个 promise 来调用该函数,以便仅在方法返回错误时调用 expect 语句。

import { Injectable } from "@angular/core";
import { HttpErrorResponse } from "@angular/common/http";

@Injectable({
  providedIn: "root"
})
export class GlobalErrorHandler {
  constructor() {}
  /**
   * If an error occurs, we display it in the console with pertinent details
   * @param error the error object
   */
  handleError(error: any) {
    if (error instanceof HttpErrorResponse) {
      const errorToShow = {
        status: error.status,
        message: error.message,
        details: error.error.message
      };
      console.error(`Backend returned this error => `, errorToShow);
    } else {
      // If error is not an instance of HttpErrorResponse...
      console.error(`An error occurred => "${error.message}"`);
    }
    throw new Error(error.message);
    // enable the following line to show notification...
    // this.errorNotifier.handleError(error);
  }
}

测试:-

import { TestBed } from "@angular/core/testing";
import { HttpErrorResponse } from "@angular/common/http";
import { GlobalErrorHandler } from "./global-error-handler.service";

describe("GlobalErrorHandler Service", () => {
  let service: GlobalErrorHandler;
  let error;
  beforeEach(() => {
    service = new GlobalErrorHandler();
    error = new HttpErrorResponse({
      url: "Some url",
      error: { message: "error message details" },
      status: 404
    });
  });
  afterEach(() => {
    service = null;
    error = null;
  });

  it("should show output error message to console", () => {
    const errorSpy = spyOn(console, "error");
    let promise = new Promise((resolve, reject) => {
      resolve(()=>service.handleError(error));
    })
    promise.then(()=> {},()=>expect(errorSpy).toHaveBeenCalled());
  });

  it("should throw error when called", () => {
    expect(() => {
      service.handleError(error);
    }).toThrow(new Error(error.message));
  });
});

【问题讨论】:

  • 是否应该在处理错误之前创建间谍?
  • 部分解决方案是在调用方法之前创建间谍,正如 Jota 所建议的那样,但另一部分是实际方法抛出错误,导致测试无法达到预期语句.所以我从方法中删除了throw error 行,测试按预期工作。我不确定为什么我把那个 throw 错误行放在那里,但是可能有一种方法可以编写测试,以便即使该方法具有 throw 语句,它也会正确断言。如果我找到它会更新。现在我已经用有效的代码更新了 OP。
  • 更新了 OP 中的解决方案,使用即使使用 throw 语句也可以工作的代码。我基本上不得不在 promise 中调用原始方法。唷,通过解决我自己的问题,我学到了很多关于测试的知识:D

标签: javascript angular unit-testing jasmine


【解决方案1】:

您在处理错误后创建了间谍,这就是断言失败的原因。

尝试以下方法:

const errorSpy = spyOn(console,"error");
service.handleError(error);
expect(errorSpy).toHaveBeenCalled();

【讨论】:

  • 试过了,得到Property 'spyOn' does not exist on type 'typeof jasmine'.我正在使用这些版本的茉莉花:-“jasmine-core”:“~2.99.1”,“jasmine-spec-reporter”:“~4.2.1 ",我也尝试按照您原则上的建议重新排列线条,但这导致了同样的错误。我已经用我尝试过的行更新了 OP。
  • @RawCode 我的错,它只是spyOn。更新答案
  • 感谢您的帮助,但没有奏效。但是在做了一些研究并参考了官方文档后,我得到了它的工作。显然 Jasmine 2.0 的语法已经改变,虽然这可以在旧版本上工作,但新版本需要不同的方式来启动和断言间谍。我用有效的代码添加了一个答案。再次感谢您的帮助:)
  • 您好,很抱歉造成这种混乱。我让代码使用不同的语法,但在这样做的同时,我还重组了服务方法本身,结果发现问题出在服务方法上,因为我尝试使用您在此处提供的代码,它也可以工作!所以我不需要改变茉莉花的语法。我正在使用有效的代码更新 OP。谢谢:)
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 2017-09-26
  • 2019-02-05
  • 1970-01-01
相关资源
最近更新 更多