您好,登錄后才能下訂單哦!
要使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。