如何在使用Angular Karma Jasmine时过滤console.log



我正在寻找一种方法来过滤出运行测试时打印到控制台的控制台日志。控制台日志对项目非常有用,但是当我们运行测试时,它们并没有提供太多帮助,而且会使输出膨胀。

我试过在我们的test.ts文件中运行这个(它在我们的angular配置文件中用于编译测试),但是它不起作用。

//...
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.less"
],
"scripts": [],
"assets": [
"src/assets",
"src/.well-known"
]
}
},
//...
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import "zone.js/dist/zone-testing";
import { getTestBed } from "@angular/core/testing";
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from "@angular/platform-browser-dynamic/testing";
//...
//bug: this errors with Error: Spies must be created in a before function or a spec
spyOn(window.console, "log").and.callFake(() => {});
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
// Then we find all the tests.
const context = require.context("./", true, /.spec.ts$/);
// And load the modules.
context.keys().map(context);

我知道我可以创建一个spy并将其导入到每个测试文件中,但是我们有很多这样的文件,这并不是一个真正可扩展的方法。

有没有办法让我每次考试都偷看一下这个?简单地说,这很容易通过使用他们的setupFiles特性来实现。

我能够通过更新我的test.ts来解决:

// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import "zone.js/dist/zone-testing";
import { getTestBed } from "@angular/core/testing";
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from "@angular/platform-browser-dynamic/testing";
//...
//bug: this errors with Error: Spies must be created in a before function or a spec
spyOn(window.console, "log").and.callFake(() => {});
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
// Then we find all the tests.
const context = require.context("./", true, /.spec.ts$/);
// And load the modules.
context.keys().map(context);
beforeEach(() => {
const ifTextMatchesThenIgnore = (text: string) => {
return (
text.toLowerCase().includes("configuring happyland") ||
text.match(/^[.*]+/) ||
text.toLowerCase().includes("stripe")
);
};
spyOnConsole("log", ifTextMatchesThenIgnore);
});
const spyOnConsole = (property: "log" | "warn" | "info" | "error", ifTextMatchesThenIgnore: Function) => {
const print = console[property];
spyOn(console, property).and.callFake(function (...args) {
let filteredArgs = [];
for (let i = 0; i < args.length; i++) {
const text = args?.[i];
try {
if (ifTextMatchesThenIgnore(text)) return;
} catch {}
filteredArgs.push(text);
}
if (filteredArgs.length > 0) {
print(...filteredArgs);
}
});
};