Angular 2 Jasmine How to test a function of a component

浪尽此生 提交于 2019-12-01 05:12:56

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()"

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']);
  })
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!