Loading...
Loading...
ALWAYS use when writing tests for Angular applications, including unit tests, component tests, service tests, or E2E tests with Jasmine, Karma, Vitest, or Cypress.
npx skill4agent add oguzhan18/angular-ecosystem-skills angular-testingComponent输入import { TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [MyComponent]
}).compileComponents();
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
});it('should calculate total correctly', () => {
// Arrange
const service = new CalculatorService();
// Act
const result = service.add(2, 3);
// Assert
expect(result).toBe(5);
});fakeAsynctickimport { fakeAsync, tick } from '@angular/core/testing';
it('should fetch data after delay', fakeAsync(() => {
service.getData();
tick(1000);
expect(component.data).toBeTruthy();
}));it('should call service', () => {
spyOn(service, 'getData').and.returnValue(of({ name: 'Test' }));
component.loadData();
expect(service.getData).toHaveBeenCalled();
});by.cssimport { By } from '@angular/platform-browser';
it('should display title', () => {
fixture.detectChanges();
const el = fixture.debugElement.query(By.css('.title'));
expect(el.nativeElement.textContent).toBe('Hello');
});// ❌ Bad - tests implementation details
expect(component['privateMethod']).toHaveBeenCalled();
// ✅ Good - tests behavior
expect(fixture.nativeElement.querySelector('.result')).toContain('expected');provideHttpClientTestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor]))
]
});const mockAuthService = {
isAuthenticated: jasmine.createSpy().and.returnValue(true),
getToken: jasmine.createSpy().and.returnValue('fake-token')
};
TestBed.configureTestingModule({
providers: [{ provide: AuthService, useValue: mockAuthService }]
});it('should show error for invalid email', () => {
component.form.controls.email.setValue('invalid');
component.form.controls.email.markAsTouched();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.error')).toBeTruthy();
});detectChanges// After changing component properties
component.value = 'new value';
fixture.detectChanges();
// For async operations
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();