Angular Vitest æµè¯å¿«éå ¥é¨ | AIçæåç¿»è¯
Question: å¦ä½ä¸º Angular 20+ 项ç®ç¼åå¹¶è¿è¡ç®åç npm testï¼
Answer:
å¨ Angular 20+ ä¸ï¼å®é ä¸ä» Angular ~v15â16 å¼å§ï¼ï¼é»è®¤ç test runner æ¯ Vitestï¼å代äºä¹åç Karma + Jasmineï¼ã
以䏿¯å¨ç°ä»£ Angular 项ç®ï¼2025â2026 飿 ¼ï¼ä¸è®¾ç½®åç¼åç®åæµè¯æå¸¸è§ä¸æ´æ´çæ¹æ³ï¼
1. Angular 20+ 䏿叏è§ä¸æ¨èçæ¹å¼ (Vitest + jsdom)
# è¿è¡æµè¯ (è¿æ¯ "npm test" å®é
æ§è¡çæä½)
npm test
# Watch mode (建议å¨å¼åè¿ç¨ä¸ä½¿ç¨)
npm run test:watch
å
¸åç package.json èæ¬å¦ä¸æç¤ºï¼
"scripts": {
"test": "ng test",
"test:watch": "ng test --watch"
}
2. æç®åçæµè¯ç¤ºä¾ (2025+ 飿 ¼)
src/app/app.component.spec.ts
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Welcome');
});
it('should have welcome message in component', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toContain('angular');
});
});
3. æ´ç®åçæ¹å¼ â æµè¯å¸¦æ signal input çç»ä»¶ (Angular 17+ 飿 ¼)
src/app/counter/counter.component.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true,
template: `
<p>Count: {{ count() }}</p>
<button (click)="increment()">+1</button>
`
})
export class CounterComponent {
count = input(0);
increment() {
// éå¸¸ä½ ä¼å¨è¿éä½¿ç¨ output æ model()
}
}
counter.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
let component: CounterComponent;
let fixture: ComponentFixture<CounterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CounterComponent]
}).compileComponents();
fixture = TestBed.createComponent(CounterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should display initial count', () => {
expect(fixture.nativeElement.querySelector('p').textContent)
.toContain('Count: 0');
});
it('should display count = 7 when input is set', () => {
fixture.componentRef.setInput('count', 7);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p').textContent)
.toContain('Count: 7');
});
});
å¿«éæ¸ å â ç°ä»£ Angular æµè¯ (2025+)
æ»ç» â æç®åçå¼å§æ¹å¼
-
ç´æ¥è¿è¡ï¼
npm test -
æä½¿ç¨ watch modeï¼å¼ºçæ¨èï¼ï¼
npm run test:watch -
æç §ä¸é¢ç示ä¾ç¼åæµè¯ â å®ä»¬å¨ Angular 17/18/19/20+ ä¸å坿£å¸¸å·¥ä½
ç¥æµè¯æå¿«ï¼
References:
- None needed for this Angular core knowledge question
