我正在尝试为我的角度控制器编写单元测试(用打字稿编写)。控制器用户数据表。我需要在测试中将DTOptionsBuilder注入控制器,但无法弄清楚如何模拟它。到目前为止,这是我的代码。
module MyApp.Controllers {
export class MyController {
dtOptions: any;
static $inject = [
"$scope"
];
constructor(
private $scope: IControllerScope,
private dtOptionsBuilder: any
) {
this.dtOptions = this.dtOptionsBuilder
.newOptions()
.withPaginationType('full_numbers')
.withDisplayLength(10)
.withOption('bInfo', false)
.withOption('bPaginate', false)
.withOption('searching', false)
.withOption('paging', false)
.withOption('order', [0, 'desc']);
}
}
}
describe("controller", () => {
var controller: MyApp.Controllers.MyController;
var dtOptionsBuilder: any;
beforeEach(angular.mock.module('app'));
beforeEach(angular.mock.module($provide => {
$provide.service('dtOptionsBuilder', function () {
this.newOptions = jasmine.createSpy('newOptions').and.callFake(() => {
return {};
});
this.withPaginationType = jasmine.createSpy('withPaginationType').and.callFake(() => {
return null;
});
this.withDisplayLength = jasmine.createSpy('withDisplayLength').and.callFake(() => {
return null;
});
this.withOption = jasmine.createSpy('withOption').and.callFake(() => {
return {};
});
});
return null;
}));
beforeEach(inject(function(_$controller_,_dtOptionsBuilder_, _$rootScope_) {
$scope = _$rootScope_.$new();
dtOptionsBuilder = _dtOptionsBuilder_;
controller = new MyApp.Controllers.MyController($scope, dtOptionsBuilder);
}));
describe("on creation ->", () => {
it("should initialize the controller", () => {
expect('test1').toBe('test1');
});
});
});
我收到错误 " this.dtOptionsBuilder.newOptions(...)。withPaginationType不是函数"
非常感谢任何帮助
答案 0 :(得分:0)
我不是100%肯定,但我认为你需要定义dtOptionsBuilder以便它可以注射:
app.factory('dtOptionsBuilder', [function() {
var dtOptionsBuilder = null; // initialize here...
return dtOptionsBuilder;
}]);
完成后你可以注射它:
export class MyController {
private dtOptions: any;
static $inject = [
"$scope",
"dtOptionsBuilder" // you need to indicate that it needs to be injected
];
constructor(
private $scope: IControllerScope,
dtOptionsBuilder: any // removed private
) {
this.dtOptions = dtOptionsBuilder.newOptions()
.withPaginationType('full_numbers')
.withDisplayLength(10)
.withOption('bInfo', false)
.withOption('bPaginate', false)
.withOption('searching', false)
.withOption('paging', false)
.withOption('order', [0, 'desc']);
}
}