Error: spy expected but received function

Here is my controller :

export class testController { static $inject: string[] = ["testService", "$mdDialog", "$state"]; constructor(public _testService: services.testService, private _mdDialog: any, private _$state: any) { this.isCurrentlyEditing = false; this.activate(); } } 

Here is my unit test for this:

  import {test as service} from './test.service'; import {test as ctrl} from './test.controller'; export function main() { describe("testController", () => { var mdDialog: angular.material.IDialogService; var state: ng.ui.IStateService; var testService: any; var controller: any; beforeEach(function () { angular.mock.module('comp.modules.addField'); }); beforeEach(function () { testService = { showCLULayer: () => { } }; }); beforeEach(module('comp')); beforeEach(inject(($injector: any) => { mdDialog = $injector.get('$mdDialog'); state = $injector.get('$state'); testService = $injector.get('testService'); controller = new ctrl.testController(testService, mdDialog, state); })); it("should Create Controller", () => { controller = new ctrl.testController(testService, mdDialog, state); spyOn(testService, 'showCLULayer').and.callThrough(); expect(controller).not.toBeNull(); expect(controller.activate).toHaveBeenCalled(); ////error Expected a spy, but got Function. }); }); } 

The test throws an error when it goes to the line:

  expect(controller.activate).toHaveBeenCalled(); 

saying that the spy expected, but got the function. Activate is a function called when the constructor of my controller is called, which I am testing. Can someone point me in the right direction, please.

I tried to add a line

  spyOn(controller, 'activate'); 

Before I expect, I get the following error.

  Expected spy activate to have been called. Error: Expected spy activate to have been called. 
+5
source share
1 answer

You need to monitor the function before checking if it is called. Try the following:

 it("should Create Controller", () => { controller = new ctrl.testController(testService, mdDialog, state); spyOn(testService, 'showCLULayer').and.callThrough(); expect(controller).not.toBeNull(); spyOn(controller, 'activate'); // < ------------Spy on the function expect(controller.activate).toHaveBeenCalled(); ////error Expected a spy, but got Function. }); 
+12
source

Source: https://habr.com/ru/post/1235736/


All Articles