javascript - 模拟服务时 Jasmine 出现问题

标签 javascript angularjs

我有一个如下所示的 Controller

(function () {

    var mockController = function ($scope, MockService) {
        $scope.message = "This is a text message";
        $scope.getCities = function () {
            return MockService.getCities();
        };

    };


    var mockService = function ($http) {
        this.getCities = function () {
            return $http.get("../rest/url", {
                headers: {
                    'Accept': 'application/yang.data+json'
                }
            });
        };
    };

    angular.module("MockApp", [])
        .service("MockService", mockService)
        .controller("MockController", mockController);

}())

我正在尝试编写一个 UT 来模拟如下服务

describe("MockController", function () {

    var $scope;

    beforeEach(function () {
        module("MockApp");
        inject(function (_$controller_, _$rootScope_, MockService) {
            $scope = _$rootScope_.$new();
            spyOn(MockService, "getCities").and.callFake(function () {
                return [{
                    city: "Bangalore"
                    , country: "India"
                }];
            });
            controller = _$controller_("MockController", {
                $scope: $scope
            });

        });
    });

    describe("Test", function () {

        it("Should be Bangalore", function () {
            $scope.getCities()
                .then(function (data) {
                    console.log("got it");
                })
        });
    });

});

它抛出一个错误说

类型错误:$scope.getCities(...).then 不是一个函数

请帮助我。

最佳答案

我认为:

$scope.getCities = function () {
  return MockService.getCities();
};

应该是:

$scope.getCities = function () {
  return MockService(getCities());
};

关于javascript - 模拟服务时 Jasmine 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37211376/

相关文章:

angularjs - 错误 : Property 'then' does not exist on type 'Hero[]'

javascript - angularjs ng-repeat中的动态互斥下拉列表

javascript - 根据 Angular 范围值更改 CSS

javascript - 配置中的 AngularJS 过滤器

javascript - 动画元素无法点击

javascript - 如何在我的应用程序中注入(inject)模板部分?

javascript - AngularJS:尝试使用服务,出现错误 "cannot read property ',然后是“未定义”

javascript - 使用 jquery 的 Kendo 开关更改事件

javascript - 设计用于使用 ajax 更新多个局部 View 的客户端

javascript - 打开图形在单页应用程序 AngularJs 中无法正常工作