在ngFor中对按钮进行单元测试的方法如下:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Component } from '@angular/core';
@Component({
template: `
<div>
<button *ngFor="let button of buttons" (click)="onClick(button)">{{ button }}</button>
</div>
`
})
class TestComponent {
buttons = ['Button 1', 'Button 2', 'Button 3'];
onClick(button: string) {
console.log('Clicked:', button);
}
}
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [TestComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should render buttons correctly', () => {
const buttons = fixture.debugElement.queryAll(By.css('button'));
expect(buttons.length).toBe(component.buttons.length);
expect(buttons[0].nativeElement.textContent).toBe(component.buttons[0]);
expect(buttons[1].nativeElement.textContent).toBe(component.buttons[1]);
expect(buttons[2].nativeElement.textContent).toBe(component.buttons[2]);
});
it('should call onClick method when a button is clicked', () => {
spyOn(component, 'onClick');
const buttons = fixture.debugElement.queryAll(By.css('button'));
buttons[0].triggerEventHandler('click', null);
expect(component.onClick).toHaveBeenCalledWith(component.buttons[0]);
});
});
ng test
这样,你就可以在ngFor中对按钮进行单元测试了。测试用例中的第一个测试确保按钮正确渲染,第二个测试验证点击按钮时是否调用了正确的方法。根据实际情况,你可以进一步扩展测试用例,测试其他功能和逻辑。
领取专属 10元无门槛券
手把手带您无忧上云