要使用Jest测试Angular组件,请按照以下步骤操作:
确保已经安装了Angular CLI和Jest。然后,在项目根目录中运行以下命令来安装所需的依赖项:
ng add @angular-builders/jest
npm install --save-dev jest-preset-angular @types/jest
在项目根目录中创建一个名为jest.config.js
的文件,并添加以下内容:
module.exports = {
preset: 'jest-preset-angular',
roots: ['<rootDir>/src'],
testMatch: ['**/+(*.)+(spec).+(ts)'],
transform: {
'^.+\\.(ts|html)$': 'ts-jest',
},
resolver: '@nrwl/jest/plugins/resolver',
moduleFileExtensions: ['ts', 'js', 'html'],
coverageReporters: ['html'],
};
tsconfig.spec.json
:将tsconfig.spec.json
中的compilerOptions
部分修改为:
"compilerOptions": {
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"strict": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"strictNullChecks": false,
"importHelpers": true,
"target": "es2015",
"module": "commonjs",
"lib": ["es2018", "dom"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
现在可以开始编写组件测试了。例如,假设有一个名为app.component.ts
的组件,可以创建一个名为app.component.spec.ts
的测试文件。以下是一个简单的测试示例:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the app', () => {
expect(component).toBeTruthy();
});
it(`should have as title 'my-app'`, () => {
expect(component.title).toEqual('my-app');
});
it('should render title', () => {
const compiled = fixture.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('my-app app is running!');
});
});
要运行测试,请在项目根目录中使用以下命令:
ng test
这将运行Jest测试并显示结果。现在已经成功地使用Jest测试了Angular组件。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。