Angular 2 Jasmine How to test a function of a component

前端 未结 2 1542
北海茫月
北海茫月 2021-01-05 14:34

How do I mock the click event of a function in Angular 2? For my Home Component I have:

Home Component

import { Component } from \'@         


        
相关标签:
2条回答
  • 2021-01-05 14:52

    You need to get the button then click it

    de.nativeElement.querySelector('.theButtonClass').click();
    

    Then check that the stub's navigate method is called with the correct argument

    expect(mockRouter.navigate).toHaveBeenCalledWith(['/about']);
    

    You may or may not need to use async. If it doesn't work, you might need to use async and wait for the asynchronous click event to stabilize

    import { async } from '@angular/core/async';
    
    it('..', async(() => {
      ...click();
      fixture.whenStable().then(() => {
        expect(mockRouter.navigate).toHaveBeenCalledWith(['/about']);
      })
    })
    
    0 讨论(0)
  • 2021-01-05 15:07

    First, I recommend you writing your test in Typescript, it keeps cohesion between your components and your tests.

    Here are the basic steps in your spec file:

    Get the element (I recommend using an Id tag if possible)

    const element = fixture.debugElement.query(By.css("#your-element"));
    

    Trigger the event. NOTE: there must be a (click) event on the element

    element.triggerEventHandler("click", null);
    

    Then detect the changes from the event

    fixture.detectChanges();
    

    In your HTML template, you would need to have click events pointed at the functions you wish to test (click)="redirectToUpload()"

    0 讨论(0)
提交回复
热议问题