Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock service function in Angular component for unit test

Tags:

I am writing unit test for angular app, I am testing if the service function returns a value.

component.spec.ts

import {TopToolBarService} from '../../top-toolbar/top-toolbar.service';  beforeEach(async(() => {    TestBed.configureTestingModule ({    declarations: [ UsersListComponent],    providers: [TopToolBarService],//tried mocking service here,still test failed    schemas:[CUSTOM_ELEMENTS_SCHEMA]  })   .compileComponents(); }));    beforeEach(() => {     fixture = TestBed.createComponent(UserListComponent);     component = fixture.componentInstance;     fixture.detectChanges();   });      it('should return data from service function', async(() => {     let mockTopToolBarService: jasmine.SpyObj<TopToolBarService>;     mockTopToolBarService = jasmine.createSpyObj('TopToolBarService', ['getCustomer']);     mockTopToolBarService.getCustomer.and.returnValue("king");     fixture.detectChanges();     expect(component.bDefine).toBe(true); //fails   }))  

component.ts

bDefine = false; ngOnInit() {  let customer = this.topToolBarService.getCustomer();  if (customer == null) {    bDefine = false;  } else {     bDefine = true;    } } 

I believe I have mocked the service function in my test, so I expect it must have reached else part where variable is set to 'true'.

TopToolBarService.ts

import { EventEmitter, Injectable, Output } from "@angular/core";  @Injectable() export class TopToolBarService { customer = null;    getCustomer() {     return this.customer;   } } 
like image 908
karansys Avatar asked Oct 10 '19 21:10

karansys


People also ask

How do I unit test a service with Angular components?

Mock Service Dependency In Angular For unit testing the method, you need to mock the service method getPosts to test the component method. Let's start by writing unit test for testing method getPostDetails when the response from service method getPosts is an empty array. Add the following unit test case to the app.

How do you mock a function in Angular testing?

A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.

Which method is used to mock the service method response in Angular?

Prefer spies as they are usually the best way to mock services. These standard testing techniques are great for unit testing services in isolation. However, you almost always inject services into application classes using Angular dependency injection and you should have tests that reflect that usage pattern.


2 Answers

Try updating providers inside beforeEach(async(() => ...) and moving your mockedService variable on the top of it:

describe('Component TEST', () => {    ...    let mockToolBarService;    ...       beforeEach(async(() => {       ...       mockToolBarService = jasmine.createSpyObj(['getCustomer']);       mockToolBarService.getCustomer.and.returnValue('king');       TestBed.configureTestingModule ({            ...            providers: [ { provide: TopToolBarService, useValue: mockToolBarService } ]            ... 

Hope it helps!

like image 90
Pedro Bezanilla Avatar answered Sep 28 '22 15:09

Pedro Bezanilla


Change your provider value

beforeEach(() => {    TestBed.configureTestingModule({       declarations: [ UsersListComponent],       providers: [{          provide: TopToolBarService,          useValue: jasmine.createSpyObj('TopToolBarService', ['getCustomer'])       }],       schemas:[CUSTOM_ELEMENTS_SCHEMA]      });      mockTopToolBarService = TestBed.get(TopToolBarService);       mockTopToolBarService.getCustomer.and.returnValue(of([])); // mock output of function    })  
like image 20
Islam Murtazaev Avatar answered Sep 28 '22 13:09

Islam Murtazaev