0
我花了數小時試圖弄清楚這一點。我寫了簡單的Angular應用程序,現在我試圖在類型腳本中測試它。TypeScript Angular Jasmine + Karma測試範圍
控制器:
export class ProductsController {
static $inject = ["ProductService", "$scope"];
constructor(public 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);
};
}
}
和測試:
describe("TestService",() => {
var mock: ng.IMockStatic;
var $httpBackend: ng.IHttpBackendService;
var service: AngularTest.Services.ProductServices;
var rootScopeFake;
var controller;
var $controller: ng.IControllerService;
var mockServiceProvider;
var prop: ng.IPromise<AngularTest.Interfaces.IProducts[]>;
var q :ng.IQService;
mock = angular.mock;
beforeEach(mock.module('app.AngularTS'));
beforeEach(() => mock.inject(function (_$httpBackend_, $injector, $rootScope, _$controller_, $q) {
$httpBackend = _$httpBackend_;
rootScopeFake = $rootScope.$new();
service = $injector.get('ProductService');
$controller = _$controller_;
q = $q;
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("Should Call API", function() {
spyOn(service, "getAllProducts").and.callFake(() => {
var deffered;
deffered = q.defer();
deffered.resolve(['xxxx', 'xxxx']);
return deffered.promise;
});
controller = new AngularTest.Controllers.ProductsController(service, rootScopeFake);
expect(service.getAllProducts).toHaveBeenCalled();
expect(rootScopeFake.allProducts).toBeDefined();
});
});
當我嘗試測試我的ProductsController我recive類型錯誤: '未定義' 不是(評估「$ scope.allProducts.length對象') 這是爲什麼 ?
我像你說的已經做了不完全,但仍然有問題。基本上我不能訪問角度控制器 - 構造器內的任何範圍值。例如,如果我試圖做期望(rootScopeFake.currentPage).toEqual(1);我recive錯誤:預計未定義等於1. –
我添加了一個更新來處理該情況...調用您的範圍 – Brocco
$摘要,你是男人。我已經浪費了一天的時間。非常感謝你 –