您好,登錄后才能下訂單哦!
要使用Jest測(cè)試Angular組件,請(qǐng)按照以下步驟操作:
確保已經(jīng)安裝了Angular CLI和Jest。然后,在項(xiàng)目根目錄中運(yùn)行以下命令來(lái)安裝所需的依賴項(xiàng):
ng add @angular-builders/jest
npm install --save-dev jest-preset-angular @types/jest
在項(xiàng)目根目錄中創(chuàng)建一個(gè)名為jest.config.js
的文件,并添加以下內(nèi)容:
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/*"]
}
},
現(xiàn)在可以開(kāi)始編寫組件測(cè)試了。例如,假設(shè)有一個(gè)名為app.component.ts
的組件,可以創(chuàng)建一個(gè)名為app.component.spec.ts
的測(cè)試文件。以下是一個(gè)簡(jiǎn)單的測(cè)試示例:
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!');
});
});
要運(yùn)行測(cè)試,請(qǐng)?jiān)陧?xiàng)目根目錄中使用以下命令:
ng test
這將運(yùn)行Jest測(cè)試并顯示結(jié)果?,F(xiàn)在已經(jīng)成功地使用Jest測(cè)試了Angular組件。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。