【发布时间】:2015-12-07 20:50:01
【问题描述】:
我花了几个小时试图弄清楚这一点。我正在尝试使用 Typescript 中的测试来测试我的 Angular 控制器(用 typeScript 编写)。我被困在将服务模拟到我的控制器中。这是代码:
控制器:
export class ProductsController {
static $inject = ["ProductService", "$scope"];
constructor(productsServices: AngularTest.Interfaces.IProductsService, $scope: any) {
productsServices.getAllProducts().then((response: ng.IHttpPromiseCallbackArg<AngularTest.Interfaces.IProducts[]>): any => {
$scope.currentPage = 1;
$scope.allProducts = <AngularTest.Interfaces.IProducts[]> response.data
$scope.cartItems = [];
$scope.modalAlerts = [];
$scope.maxItems = 3;
$scope.totalItems = $scope.allProducts.length;
$scope.itemsOnPage = $scope.allProducts.slice(0, $scope.maxItems);
});
$scope.pageChanged = function () {
$scope.itemsOnPage = $scope.allProducts.slice(($scope.currentPage - 1) * $scope.maxItems, $scope.currentPage * $scope.maxItems);
};
}
}
服务:
module AngularTest.Services{
class ProductServices implements AngularTest.Interfaces.IProductsService{
httpService: ng.IHttpService
static $inject = ["$http"];
constructor($http: ng.IHttpService)
{
this.httpService = $http;
}
getAllProducts(): ng.IPromise<AngularTest.Interfaces.IProducts[]> {
return this.httpService.get('/api/Angular');
};
}
factory.$inject = ['$http'];
function factory($http : ng.IHttpService) {
return new ProductServices($http);
}
angular
.module('app.AngularTS')
.factory('ProductService', factory);
}
测试:
describe("TestService", () => {
var mock: ng.IMockStatic;
var $httpBackend: ng.IHttpBackendService;
var service; //AngularTest.Interfaces.IProductsService;
var rootScopeFake;
var controller;
var $controller: ng.IControllerService;
mock = angular.mock;
beforeEach(mock.module('app.AngularTS'));
beforeEach(() => inject(function (_$httpBackend_, $injector, $rootScope, _$controller_) {
$httpBackend = _$httpBackend_;
rootScopeFake = $rootScope.$new();
service = $injector.get('ProductService');
$controller = _$controller_;
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("Should Call API", function () {
controller = $controller('ProductsController', { ProductService: service, $scope: rootScopeFake});
spyOn(service, "getAllProducts");
expect($httpBackend.expectGET('/api/Angular').respond([
{ "x": "xx", "xxx": "xxxx", "xxxxx": 5 },
{ "x": "xx", "xxx": "xxxx", "xxxxx": 5.5 },
{ "x": "xx", "xxx": "xxxx", "xxxxx": 6 },
{ "x": "xx", "xxx": "xxxx", "xxxxx": 0 }
])).toHaveBeenCalled;
expect(service.getAllProducts).toHaveBeenCalled(); // this fails why ?
$httpBackend.flush();
});
});
我不知道为什么这不起作用,我收到了。预计间谍 getAllProducts 已被调用。
【问题讨论】:
标签: angularjs testing typescript jasmine