1. 组件生命周期:
测试组件的生命周期钩子是很常见的场景。你可以通过 spyOn 来监视这些钩子的调用。
it('should call ngOnInit', () => {
spyOn(component, 'ngOnInit');
fixture.detectChanges();
expect(component.ngOnInit).toHaveBeenCalled();
});
2. 输入属性:
测试输入属性的变化是否会触发组件的更新。
it('should update component based on input property', () => {
component.someInput = 'initial value';
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('initial value');
component.someInput = 'updated value';
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('updated value');
});
3. 输出属性:
测试输出属性是否能够正确地发射事件。
it('should emit an event', () => {
spyOn(component.someOutput, 'emit');
component.triggerEvent();
expect(component.someOutput.emit).toHaveBeenCalled();
});
4. DOM 操作:
测试组件与 DOM 的交互,检查元素是否正确渲染。
it('should render specific content', () => {
component.someProperty = 'test';
fixture.detectChanges();
const element = fixture.nativeElement.querySelector('.test-class');
expect(element.textContent).toContain('test');
});
5. 表单交互:
测试组件中的表单操作,包括输入、点击按钮等。
it('should update form value on input', () => {
const input = fixture.nativeElement.querySelector('input');
input.value = 'test';
input.dispatchEvent(new Event('input'));
expect(component.form.value.someControl).toBe('test');
});
it('should submit form on button click', () => {
spyOn(component, 'onSubmit');
const button = fixture.nativeElement.querySelector('button');
button.click();
expect(component.onSubmit).toHaveBeenCalled();
});
6. 依赖服务:
模拟依赖服务,并测试组件与服务的交互。
import { YourService } from './your.service';
describe('YourComponent', () => {
let component: YourComponent;
let fixture: ComponentFixture<YourComponent>;
let yourServiceMock: jasmine.SpyObj<YourService>;
beforeEach(() => {
const spy = jasmine.createSpyObj('YourService', ['getData']);
TestBed.configureTestingModule({
declarations: [YourComponent],
providers: [
{ provide: YourService, useValue: spy },
],
});
yourServiceMock = TestBed.inject(YourService) as jasmine.SpyObj<YourService>;
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
});
it('should call service method on component method call', () => {
component.callServiceMethod();
expect(yourServiceMock.getData).toHaveBeenCalled();
});
});
这只是一些 Angular 组件测试场景的示例,实际应用中可能涉及到更多的情况。通过深入学习 Angular 的测试工具和技术,你可以更好地覆盖你的组件,并确保应用的可靠性和稳定性。
转载请注明出处:http://www.pingtaimeng.com/article/detail/4959/Angular