簡體   English   中英

如何使用 Jasmine 單擊按鈕元素?

[英]How to click button element with Jasmine?

我需要知道確認警報中發生了什么,但為此,我需要單擊其中一個警報按鈕。 我沒有成功地做到這一點。

主要組件.ts

async signOut() {

    const {
      ["modules.organizations.main.sign_out.confirmation.title"]: title,
      ["modules.organizations.main.sign_out.confirmation.message"]: message,
      ["modules.organizations.main.sign_out.confirmation.cancel"]: cancel,
      ["modules.organizations.main.sign_out.confirmation.ok"]: ok,
    } = await this.translate.get([
      "modules.organizations.main.sign_out.confirmation.title",
      "modules.organizations.main.sign_out.confirmation.message",
      "modules.organizations.main.sign_out.confirmation.cancel",
      "modules.organizations.main.sign_out.confirmation.ok"
    ]).pipe(first()).toPromise()

    //I need to know what happens inside here after click in button.
    this.alert.confirmation(title, message, cancel, ok).afterClosed()
    .subscribe(async value => {

      if(!value.ok) return
      const loading = this.alert.loading()
      
      try {
        await this.messaging.deleteToken()
        await this.firestore.devices(this.user.uid).doc(this.messaging.uuid()).update({ deleted: true, deletedAt: this.firestore.now })
        await this.auth.signOut()
        loading.close()
      } catch (error) {
        loading.close()
        await this.auth.signOut()
      }
    })
  }

main.component.spec.ts

fdescribe('MainComponent', () => {
  let component: MainComponent;
  let fixture: ComponentFixture<MainComponent>;
  let bottomSheetMock: jasmine.SpyObj<any>;
  let alertServiceMock: jasmine.SpyObj<any>;
  let dialogRefSpy: jasmine.SpyObj<any>;
  let functionsServiceMock: jasmine.SpyObj<any>;
  let messagingServiceMock: jasmine.SpyObj<any>;
  let routerMock: jasmine.SpyObj<any>;
  let router: Router;
  let el: DebugElement;
  
  bottomSheetMock = jasmine.createSpyObj('MatBottomSheet', ['open']);
  bottomSheetMock.open.and.returnValue('true');

  dialogRefSpy = jasmine.createSpy();
  dialogRefSpy.component = {title: 'error', message: 'error'};
  dialogRefSpy.afterClosed = () => of(true);

  const matDialogSpy = jasmine.createSpyObj('MatDialog', [
    'open',
    'close',
  ]);
  matDialogSpy.open.and.returnValue(dialogRefSpy);
  matDialogSpy.close.and.returnValue(dialogRefSpy);

  beforeEach(waitForAsync(() => {
    messagingServiceMock = jasmine.createSpyObj('MessagingService', [
      'requestPermission'
    ]);
    messagingServiceMock.requestPermission.and.callThrough();

    routerMock = jasmine.createSpyObj('Router',[
      'navigate'
    ]);
    routerMock.navigate.and.returnValue(true);

    alertServiceMock = jasmine.createSpyObj('AlertService',[
      'message',
      'error',
      'input',
      'password',
      'loading',
      'confirmation'
    ]);
    alertServiceMock.error.and.returnValue(matDialogSpy.open(AlertComponent, {
      data: { 
        type: 'error',
        title: 'error',
        error: 'description'
      },
      disableClose: true
    }));
    alertServiceMock.input.and.returnValue(matDialogSpy.open(AlertComponent, {
      data: { 
        type: 'input', 
        title: 'title', 
        description: 'description'
      },
      disableClose: true
    }));
    alertServiceMock.confirmation.and.returnValue(matDialogSpy.open(AlertComponent, {
      data: { 
        type: 'confirmation', 
        title: 'title', 
        message: 'message', 
        cancel: 'cancel', 
        ok: true
      },
      disableClose: true
    }))
    alertServiceMock.loading.and.returnValue(matDialogSpy);
    alertServiceMock.message.and.callThrough();

    TestBed.configureTestingModule({
      imports: [
        NoopAnimationsModule,
        AngularFireModule.initializeApp(environment.firebase),
        AngularFirestoreModule,
        OverlayModule,
        RouterTestingModule,
        MatDialogModule,
        MatChipsModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: TranslateFakeLoader
          }
        })
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      declarations: [
        MainComponent
      ],
      providers: [
        { provide: AlertService, useValue: alertServiceMock },
        { provide: MatDialog, useValue: matDialogSpy },
        { provide: MatBottomSheet, useValue: bottomSheetMock },
        { provide: Router, useValue: routerMock },
        { provide: MessagingService, useValue: messagingServiceMock },
        AuthService,
        TranslateService,
        UploadService,
        FormBuilder,
      ],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MainComponent);
    bottomSheetMock = TestBed.inject(MatBottomSheet);
    alertServiceMock = TestBed.inject(AlertService);
    messagingServiceMock = TestBed.inject(MessagingService);
    component = fixture.componentInstance;
    el = fixture.debugElement;
  });

  afterEach(() => {
    fixture.destroy();
  });

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

  it('should display confirmation alert', fakeAsync(async () => {
    await component.signOut();
    await fixture.whenStable();
    let buttonDebugElems: DebugElement[] = fixture.debugElement.queryAll(By.css('.mat-button'));
    console.log('elements =>');
    console.log(buttonDebugElems); // Here, I have 0 elements.
    
    expect(await alertServiceMock.confirmation).toHaveBeenCalled();
  }));
});

Obs:生成警報時,會生成一個按鈕元素。 但即使在 debugElement 中搜索按鈕,我也找不到任何東西。

嘗試在fixture.detectChanges fixture.whenStable運行更改檢測,並希望該按鈕將在那里。

  it('should display confirmation alert', fakeAsync(async () => {
    await component.signOut();
    await fixture.whenStable();
    fixture.detectChanges(); // add a fixture.detectChanges() for change detection to run
    // and maybe it will paint the button then.
    let buttonDebugElems: DebugElement[] = fixture.debugElement.queryAll(By.css('.mat-button'));
    console.log('elements =>');
    console.log(buttonDebugElems); // Here, I have 0 elements.
    
    expect(await alertServiceMock.confirmation).toHaveBeenCalled();
  }));

我設法解決了這個問題,組件沒有被渲染,因為它有 *ngIf 返回 false。 如果有人遇到同樣的問題,請檢查組件是否正在渲染:

console.log(fixture.debugElement);

在控制台中,您可以查看 html 的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM