【发布时间】:2021-03-23 18:35:48
【问题描述】:
我创建了一个服务,它可以容纳多个组件共享的逻辑。尝试为它编写单元测试,但是当我运行ng test 时,它只运行组件规范文件。即使我在*.service.spec.ts 文件中使用fdescribe,它似乎也忽略了它。
以前,这不是问题。
我检查了所有配置,仔细检查了拼写,编写了失败的测试用例等。
testing-file.service.ts
@Injectable({
providedIn: 'root'
})
export class TestingFileService {
constructor() { }
/**
* Function to test
*/
runTest(): string{
return 'Testing'
}
}
testing-file.service.spec.ts
describe('TestingFileService', () => {
let service: TestingFileService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ScheduleValidationService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should run test', () => {
const result = service.runTest();
expect(result).toMatch('Testing');
});
}
karma.conf.js
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-firefox-launcher'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage/[app-name]'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 8080,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: true,
restartOnFileChange: true
});
};
编辑 3/24 - 添加了 test.ts 文件:
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';
declare const require: any;
//First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.component\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
【问题讨论】:
-
你能不能也提供你的'/src/test.ts'文件
-
当然,刚刚添加。看了一下,会不会是
context? -
这是股票 CLI 的正则表达式:
const context = require.context('./', true, /\.spec\.ts$/);。试试这个,希望它可以工作。
标签: angular unit-testing karma-jasmine