gpt4 book ai didi

javascript - 无法获得涉及 Angular 上的 Jasmine spy 的有效断言

转载 作者:行者123 更新时间:2023-11-30 19:52:11 31 4
gpt4 key购买 nike

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

该服务工作正常,甚至在 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

浏览器测试实例截图:-

Screenshot showing the desired console.error output, but also its test failing

我希望测试能够通过,尤其是当浏览器实际返回 console.error 时。我是测试和 Jasmine 的新手。所以这可能有些愚蠢,请帮帮我。提前致谢:)

更新:-

尝试重新排列行以在调用服务之前创建 spy (在 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 语句在它到达 expect 语句之前取消了测试。在这里,我使用 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));
});
});

最佳答案

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

尝试以下操作:

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

关于javascript - 无法获得涉及 Angular 上的 Jasmine spy 的有效断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54364950/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com