angularjs - 错误 : Expected a spy, 但得到了函数

标签 angularjs jasmine karma-jasmine

这是我的 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();
    }
    }

这是我的 单元测试 为了那个原因:
  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();

说 期待 spy ,但得到了功能。 Activate 是一个函数,当我调用正在测试的 Controller 的构造函数时会调用该函数。请有人指出我正确的方向。

尝试添加该行
    spyOn(controller, 'activate'); 

在期望之前,我收到以下错误。
   Expected spy activate to have been called.
   Error: Expected spy activate to have been called.

最佳答案

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

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

关于angularjs - 错误 : Expected a spy, 但得到了函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33659757/

相关文章:

javascript - 如何在 AngularJS 的页面上找到第一个键 "id"?

javascript - 在 AngularJs SPA 中,如何从 URL 中删除 ".html"

javascript - 使用 jasmine 模拟对服务器的调用

javascript - 从 WebStorm 运行 Jasmine 测试

unit-testing - Angular 2.0.0 - 模拟文件 uploader

javascript - Angular md-input-container 调整大小

javascript - 使用 ng-repeat AngularJS 构建大表后,Internet Explorer 中的垃圾收集需要很长时间

javascript - e2e Protractor 测试无法检测多层 Angular 路由器中的 Angular 分量

javascript - 在服务单元测试中订阅模拟变量

javascript - 正则表达式设置单元测试文件路径