简体   繁体   English

TypeScript Angular Jasmine + Karma测试

[英]TypeScript Angular Jasmine+Karma test

I spend hours trying to figure this out. 我花了几个小时试图解决这个问题。 I'm trying to test my Angular controller (wrote in typeScript) with tests also in Typescript. 我正在尝试使用Typescript中的测试来测试我的Angular控制器(在typeScript中编写)。 I'm stuck on mocking service into my controller. 我被困在控制器的模拟服务中。 Here is the code : 这是代码:

Controller : 控制器:

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

Service : 服务内容:

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

}

Test : 测试:

    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();

    });
});

I don't know why this isn't working i recive.Expected spy getAllProducts to have been called. 我不知道为什么我不喜欢它。期望的间谍getAllProducts被调用。

You should create your spy before the method you're spying on is used. 您应该在使用所监视的方法之前创建间谍。 Since the method is used in the controller constructor. 由于该方法用于控制器构造函数中。 The spy should be created before initiating your controller. 应该在启动控制器之前创建间谍。

it("Should Call API", function () {        
    spyOn(service, "getAllProducts").and.callFake(function(){
        //return promise
    });

    controller = $controller('ProductsController', { ProductService: service, $scope: rootScopeFake});

    ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM