解决方法1:使用Angular Karma和Jasmine
首先,确保已经安装了Angular CLI和Node.js。
npm install karma jasmine karma-jasmine karma-chrome-launcher --save-dev
karma.conf.js
文件,并添加以下内容:module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'src/**/*.spec.ts'
],
exclude: [],
preprocessors: {
'src/**/*.spec.ts': ['@angular/cli']
},
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('@angular/cli/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
package.json
文件中,将test
脚本修改为:"test": "ng test --code-coverage"
src/app/app.component.spec.ts
,并添加以下内容:import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
}));
});
npm test
解决方法2:使用Angular Karma和Jest
首先,确保已经安装了Angular CLI和Node.js。
npm install karma jest @types/jest @angular-builders/jest --save-dev
karma.conf.js
文件,并添加以下内容:module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jest'],
files: [
'src/**/*.spec.ts'
],
exclude: [],
preprocessors: {
'src/**/*.spec.ts': ['@angular/cli']
},
plugins: [
require('karma-jest'),
require('@angular/cli/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
package.json
文件中,将test
脚本修改为:"test": "ng test --karma-config karma.conf.js"
src/app/app.component.spec.ts
,并添加以下内容:import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({