Angularjs 错误:应为间谍,但已获取函数
这是我的控制器:Angularjs 错误:应为间谍,但已获取函数,angularjs,jasmine,karma-jasmine,Angularjs,Jasmine,Karma Jasmine,这是我的控制器: export class testController { static $inject: string[] = ["testService", "$mdDialog", "$state"]; constructor(public _testService: services.testService, private _mdDialog: any, private _$state: any) { this.isCurrentlyEdit
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.
在测试函数是否被调用之前,需要监视函数。试试这个:
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.
});
it(“应该创建控制器”,()=>{
controller=new ctrl.testController(testService,mdDialog,state);
spyOn(testService,'showCLULayer')。和.callThrough();
expect(controller.not.toBeNull();
spyOn(控制器,“激活”);//<------监视该功能
expect(controller.activate).toHaveBeenCalled();
////错误应为间谍,但获得了函数。
});
尝试添加spyon,它抛出了预期已调用spy activate的新错误。错误:预期已调用spy activate。在监视函数时,可能应该尝试使用和.callThrough
,例如:spyOn(控制器,'activate')。和.callThrough()代码>好,那么您现在得到了一个正式的测试失败。在控制器实例化期间是否调用了activate
函数?是,正在调用该函数。