如何在茉莉花角组件中单击以触发ngClass更改

时间:2019-04-12 20:16:09

标签: angular jasmine components karma-runner

该点击似乎没有被触发,也没有将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。

1 个答案:

答案 0 :(得分:1)

您正在监视将isActive的按钮属性设置为true的函数:

spyOn(component, 'onClick');

当您窥探一个函数时,除非在spyOn函数的末尾添加.and.callThrough(),否则它不会被调用。如果您删除间谍,我希望它能起作用。

或者,它可以是:

spyOn(component, 'onClick').and.callThrough();

...但是我不确定为什么首先要监视该功能。