Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing that a component method calls another method

Given this simple component :

import { Component} from '@angular/core';  @Component({   selector: 'app-component' }) export class AppComponent {   foo() {     this.bar();   }    bar() {     console.log('hello');   } } 

How come the following test won't validate that bar is called when I call foo

describe('AppComponent', () => {   let component: AppComponent;      beforeEach(() => {     component = new AppComponent();   }    it('should foobar', () => {     component.foo();     spyOn(component, 'bar');     expect(component.bar).toHaveBeenCalled();   })  } 

I get the failed test :

Expected spy bar to have been called. 
like image 397
Lev Avatar asked Feb 17 '17 15:02

Lev


People also ask

How do you call another component function?

To call another components function in Angular, we can inject the component we want to call the function on as a dependency. export class OneComponent implements OnInit, AfterViewInit { //... ngOnInit() {} public testCall() { alert("I am here.."); } //... }

How do you call a method in component from service?

The question does not ask component interaction, it asks for calling a component method from a service. This simply can be achieved by injecting service to the component. Then define a method inside the service which takes a function as parameter.

What is fixture detectChanges ()?

fixture is a wrapper for our component's environment so we can control things like change detection. To trigger change detection we call the function fixture.detectChanges() , now we can update our test spec to: Copy it('login button hidden when the user is authenticated', () => { expect(el. nativeElement. textContent.


1 Answers

You need to set up the spy before the method is called. Jasmine spys wrap function to determine when they are called and what they get called with. The method must be wrapped before the spied on method is called in order to capture the information. Try changing your test to match the following:

it('should foobar', () => {     spyOn(component, 'bar');     component.foo();     expect(component.bar).toHaveBeenCalled(); }) 
like image 87
Teddy Sterne Avatar answered Oct 15 '22 20:10

Teddy Sterne