Uttam Singapura
Uttam Singapura

Reputation: 97

Unit Testing events in karma angular 2 application

I'm trying to unit test the method abc(Event) using karma. I have a dropdown in my view page which has 4 options which up on change will trigger abc(Event) method.

Here is my view page:

<div class="myClass">
<select (change)="abc($event)" id="my">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
    <option value="four">Four</option>
</select>

my component.ts file contains the definition of method abc.

import {Component,OnInit} from '@angular/core';
import { LocaleService } from '../../../services/locale.service';
@Component({
selector: 'app-localeselector',
templateUrl: './localeselector.component.html',
styleUrls: ['./localeselector.component.scss']
})


export class LocaleselectorComponent implements OnInit{

 private localeService: any;
 private language;
 constructor() { }

 ngOnInit() { }

}

abc(ev: Event) {
    //something...
}
}

How can I test method abc? Also how to mock $event? Thanks in advance.

Upvotes: 3

Views: 1888

Answers (1)

Uttam Singapura
Uttam Singapura

Reputation: 97

Thanks, it worked!!! :) I found the solution. Was able to mock the event by sending in an object.

it('should work', () => {
    component.abc({ srcElement: { value: 'xyz' } });
    expect(someMethod.getValue()).toEqual('xyz');
});

I also changed the abc method in my component.ts file to

abc($event){
    //do something...
}

Upvotes: 2

Related Questions