【问题标题】:Error: Expected a spy, but got Function错误:预期是间谍,但得到了功能
【发布时间】:2016-02-13 02:06:09
【问题描述】:

这是我的控制器:

    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();
    }
    }

这是我的单元测试:

  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.      
    });       

});
}

测试到行时抛出错误:

 expect(controller.activate).toHaveBeenCalled();

说期望一个间谍,但得到了功能。 Activate 是一个在我调用我正在测试的控制器的构造函数时被调用的函数。请有人指出我正确的方向。

尝试添加行

    spyOn(controller, 'activate'); 

出乎意料,我收到以下错误。

   Expected spy activate to have been called.
   Error: Expected spy activate to have been called.

【问题讨论】:

  • 好的,所以你现在正式测试失败了。 activate 函数是否在您的控制器实例化期间被调用?
  • 是的,它正在被调用。

标签: angularjs jasmine karma-jasmine


【解决方案1】:

在测试函数是否被调用之前,您需要监视该函数。试试这个:

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.      
    });    

【讨论】:

  • 尝试添加间谍,它会抛出这个新错误 预期间谍激活已被调用。错误:预期的间谍激活已被调用。
  • 也许你应该在窥探函数时尝试使用and.callThrough,例如:spyOn(controller, 'activate').and.callThrough();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多