点击似乎没有被触发,并且没有在我试图点击的按钮上将ngClass更改为活动状态。
--
HTML:
<div class='btn-group' role='group' aria-label="">
<button type='button'
id='btn-group-btn-{{i}}'
*ngFor="let button of buttons; index as i"
(click)="onClick($event, i)"
[ngClass]="{'active': button.isActive}"
class='btn btn-default btn-primary'>
{{button.displayTxt}}
</button>
</div>
零件:
export class AdmitOneBtnGroup {
@Input() public btnDisplayText: string;
@Input() public id: string;
@Output() public clickEvent = new EventEmitter();
@Input() public buttons: Array<ButtonGroupButton>; // Should be array of objects
public onClick($event, btnIndx) {
this.buttons.forEach((button, currentIndx) => {
button.isActive = (currentIndx === btnIndx);
});
this.clickEvent.emit(btnIndx);
}
};
export interface ButtonGroupButton {
isActive: boolean,
displayTxt: string,
}
测试:
let component: AdmitOneBtnGroup;
let fixture: ComponentFixture<AdmitOneBtnGroup>;
const testData: Array<ButtonGroupButton> = [
{
displayTxt: "abc",
isActive: true,
},
{
displayTxt: "def",
isActive: false,
},
{
displayTxt: "ghi",
isActive: false,
},
]
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AdmitOneBtnGroup],
}).compileComponents()
}));
beforeEach(() => {
fixture = TestBed.createComponent(AdmitOneBtnGroup);
component = fixture.componentInstance;
component.buttons = testData;
component.id = 'button-group'
fixture.detectChanges();
});
it('#AdmitOneBtnGroupComponent button click should activate new button', async(() => {
spyOn(component, 'onClick');
const btn: HTMLElement = fixture.debugElement.nativeElement.querySelector('#btn-group-btn-1')
const clickEvent = new Event('click');
btn.dispatchEvent(clickEvent)
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(btn.getAttribute('class')).toContain("active");
})
}));
测试应该是单击第二个按钮并向其添加活动类,但活动类仍保留在第一个按钮上。
我上面有一个事件,表示expect(component.onClick).toHaveBeenCalled();出来是真的所以我不确定点击是不是被触发,或者它是否只是没有被改变的ngClass。
你在监视在这里将isActive的按钮属性设置为true的函数:
spyOn(component, 'onClick');
当您监视函数时,除非您将.and.callThrough()添加到spyOn函数的末尾,否则不会调用它。如果你删除了间谍,我希望它可以工作。
或者,它可以是:
spyOn(component, 'onClick').and.callThrough();
......但我不确定你为什么要首先监视这个功能。