如何正确触发单元测试中的按钮单击

时间:2019-11-12 22:43:10

标签: angular typescript unit-testing karma-jasmine

我创建了一个组件,该组件在HTML模板中放置了一个按钮,当按下该按钮时会触发click事件,并执行“ removeAccount”方法。我正在尝试在规格文件中应用单元测试,但是触发按钮单击没有任何反应。

  it('Should be able to accept and remove accountIdentifiers', async(() => {

    const adentifier_1: AccountIdentifier = {
      accountName: 'Rachel\'s account',
      accountCode: 'ACC_1'
    };
    const adentifier_2: AccountIdentifier = {
      accountName: 'David\'s account',
      accountCode: 'ACC_1'
    };

    const id_1 = new AccountIdentifier(adentifier_1.accountCode, adentifier_1.accountName);
    const id_2 = new AccountIdentifier(adentifier_2.accountCode, adentifier_2.accountName);
    let accountsIds = Array<AccountIdentifier>();
    accountsIds.push(id_1);
    accountsIds.push(id_2);

    component.accounts = accountsIds;

    fixture.detectChanges();

    const accountRecieverRows = fixture.debugElement.query(By.css('#accountReciever tr:nth-child(1) td'));
    const tableData: HTMLElement = accountRecieverRows.nativeElement;
    expect(tableData.textContent).toContain(adentifier_1.accountName);

    const removeAccountSpy = spyOn(component, 'removeAccount');
   const btnDeleteAccount = <HTMLButtonElement>fixture.debugElement.query(By.css('button')).nativeElement;
   btnDeleteAccount.click();

   btnDeleteAccount.dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(removeAccountSpy).toHaveBeenCalled();
  }));

任何想法?

0 个答案:

没有答案