要在Angular中运行单个或一组单元测试,你需要使用Karma测试运行器和Jasmine测试框架
.spec.ts
结尾。例如,要为example.component.ts
创建一个测试文件,可以创建名为example.component.spec.ts
的文件:import { ExampleComponent } from './example.component';
describe('ExampleComponent', () => {
let component: ExampleComponent;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ExampleComponent ]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
angular.json
文件中配置测试环境。找到test
字段并将其配置为以下格式:"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
}
}
karma.conf.js
文件中配置Karma。确保你已正确配置了所有需要的环境和依赖项。例如:module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
files: [
'src/**/*.spec.ts'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
ng test --include src/app/example/example.component.spec.ts
如果要运行一组测试,可以使用通配符*
指定多个文件:
ng test --include src/app/**/*.spec.ts
--include
标志:ng test
这样,你就可以在Angular中运行单个或一组单元测试了。在开发过程中,请确保你的测试覆盖率足够高,以便在更改代码时能够快速发现问题。
领取专属 10元无门槛券
手把手带您无忧上云