【问题标题】:Unit tests for alert controller in ionic离子警报控制器的单元测试
【发布时间】:2020-09-17 00:20:49
【问题描述】:

我正在学习用 ionic 编写单元测试,但无法为 AlertController 编写测试。下面附上代码

Terms.page.ts 文件

 export class TermsPage {
      constructor(private router: Router, private alertController: AlertController) {}
    
      onAgreeClick() {
        this.router.navigate(['/register']);
      }
    
      onDeclineClick() {
        this.presentAlertConfirm();
      }
    
      async presentAlertConfirm() {
        const alert = await this.alertController.create({
          message: 'Please agree to our terms and conditions to be able to use this application!',
          buttons: [
            {
              text: 'Agree',
              cssClass: 'primary',
              handler: () => {
                this.onAgreeClick();
              },
            },
            {
              text: 'Maybe later',
              role: 'cancel',
              cssClass: 'secondry',
            },
          ],
        });
        await alert.present();
      }
    }

Terms.spec.ts

import { DebugElement } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Router, RouterModule } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { EmptyTestComponent } from '@test-utils';

import { TermsPage } from './terms.page';

fdescribe('TermsConditionsComponent', () => {
  let component: TermsPage;
  let fixture: ComponentFixture<TermsPage>;
  let de: DebugElement;
  let router: Router;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [TermsPage],
      imports: [
        RouterModule.forRoot([]),
        RouterTestingModule.withRoutes([{ path: '**', component: EmptyTestComponent }]),
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(TermsPage);
    component = fixture.componentInstance;
    de = fixture.debugElement;

    router = TestBed.inject(Router);
    fixture.detectChanges();
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should be able to agree and go to registration on click', async () => {
    const agreeButton = de.query(By.css('#button-agree')).nativeElement as HTMLIonButtonElement;
    agreeButton.click();
    await fixture.whenStable();
    expect(router.url).toBe('/register');
  });

  it('should be able to trigger popup on click of disagree click', async () => {
    const disagreeButton = de.query(By.css('#button-disagree')).nativeElement as HTMLIonButtonElement;
    disagreeButton.click();
    await fixture.whenStable();
    expect(component.presentAlertConfirm).toBeTruthy();
  });
});

我需要达到 100% 的覆盖率

如果有人可以帮助我编写测试用例来涵盖警报按钮操作并呈现,我将不胜感激。提前致谢

【问题讨论】:

    标签: unit-testing ionic-framework alert


    【解决方案1】:

    看来您需要将测试分成两部分:

    • 测试 #1 以了解 alertcontroller.create 的用法 - 已使用适当的参数调用 to
    • 并测试 #2 的按钮处理程序

    First 可以通过标准 jasmine 调用轻松模拟,例如 .toHaveBeenCalledWith(...):

    const alertControllerStub = jasmine.createSpyObj('AlertController', ['create']);
    ...
    expect(alertControllerStub.create).toHaveBeenCalledWith(options);
    

    第二个,你需要手动触发“ok”/“cancel”并捕获两种情况下执行的方法

    const ({buttons}) = alertControllerStub.create.calls.first().args[0];
    buttons[0].handler();
    expect(smth_should_called_in_handler).toHaveBeenCalled();
    

    【讨论】:

    • Test1 中的 options 和 test 2 中的按钮代表什么?
    • 对于test1,你必须准备testOptions,jasmine会自动将它与来自组件/应用程序的incmonig进行比较
    • 对于 test2,它从你的组件代码中获取按钮 async presentActionConfirm...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2017-06-26
    相关资源
    最近更新 更多