angular如何进行单元测试呢?
以angular15为例,cli默认已安装了karma,我们只需把相关的配置文件搞定,就可以进行单元测试了。
package.json
{
"name": "hello-world",
"version": "1.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test"//单元测试命令
},
...
我们可以运行npm test运行单元测试,如果要生成报告文件,则改成:
"test": "ng test --code-coverage"
angular.json
...
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main":"src/test.ts",
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [],
"scripts": [],
"karmaConfig": "karma.conf.js"
}
}
对angular.json搜索test配置项,这里对单元测试进行了总体配置,我们还需要新建两个文件:karma.conf.js和test.ts。
前者是karma的配置文件,后者是入口文件。这里需要注意的是,test.ts的编译是在tsconfig.spec.json里,需要添加一下,否则会报错,这个后面会提到。
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-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
jasmine: {
// you can add configuration options for Jasmine here
// the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
// for example, you can disable the random execution with `random: false`
// or set a specific seed with `seed: 4321`
},
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true // removes the duplicated traces
},
coverageReporter: {
dir: require('path').join(__dirname, './coverage/testhys'),//生成报告文件
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'text-summary' }
]
},
files: [],
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true,
});
};
src/test.ts
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import "zone.js/testing";
import { getTestBed } from "@angular/core/testing";
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from "@angular/platform-browser-dynamic/testing";
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
angular15跟14相比还是有很大改动的,比如这里,14的写法还添加了这么几行:
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
如果加上的话会在angular15运行报错,需要注意。
tsconfig.spec.json
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts",
"src/test.ts"//单元测试入口
]
}
这个文件是用来编译单元测试的ts文件的,一定注意添加最后一行,否则test.ts不会编译而报错。
app.component.spec.ts
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
AppComponent
],
schemas: [ NO_ERRORS_SCHEMA ]//忽略掉不认识的那些元素和属性,并且不会报错
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title '光伏项目'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
console.log(app);
expect(app.title).toEqual('光伏项目');
});
});
随便写一个测试用例,运行一下npm test看下结果。
全正确页面:
![](https://img.haomeiwen.com/i7455247/db432675a4c56910.png)
有报错页面:
![](https://img.haomeiwen.com/i7455247/1a7d8bc965f64241.png)
网友评论