如何使用Jasmine正确实例化对象?

时间:2014-04-03 11:15:49

标签: javascript angularjs jasmine

在我的Jasmine测试中,我正在调用函数$scope.init();

在我的“真实”控制器中,我调用$scope.question.answered(),当然,我的测试也调用此方法,或尝试调用它。

但即使没有为它编写测试,我也会收到以下错误:

  

对象问题没有回答方法

我在另一个测试中得到了这个问题,所以我有一个问题对象。

但是,到目前为止,我找不到使用Jasmine正确实例化对象的方法。

  

如何在所有测试中使对象可用

编辑: 我的AngularJS控制器如下所示:

angular.module('app')


.controller('ctrl', function ($location, $scope, $routeParams) {
    $scope.init = function () {
        if (!object) {
            var stored_params = JSON.parse($.cookie("stored_params"));
            var init_url = replace_multiple(config.init_url, stored_params);
            var init_url = init_url + '?' + $.param(stored_params);
            $location.url(init_url);
            return;
        }

        console.log("$routeParams", $routeParams);

        $scope.question = object.by_id($routeParams.id);

        if ($scope.question && ($scope.question != oject.first_question())) {
            if ($scope.question.answered()) {
                // go to the normal question
            } else if ($scope.question != object.next_question(object.last_answered_question())) {
                $location.path(object.next_question(SURVEY.last_answered_question()).url);
            }
        }
    }

    $scope.init();

    GaWrapper.send_ga_page($location.path());
});

和我的测试:

    describe("Controller: QuestionCtrl", function () {

    var ctrl;
    var scope;
    var location;
    var routeParams;

    beforeEach(function () {
        object = new Survey(object_JSON.object);
        spyOn(GaWrapper, "send_ga_page");
    });

    // load the controller"s module
    beforeEach(module("app"));

    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope, $location, $routeParams) {
        scope = $rootScope.$new();
        location = $location;
        routeParams = $routeParams

        ctrl = $controller("ctrl", {
            $scope: scope,
            $location: location,
            $routeParams: routeParams
        });
    }));

    it("load the proper question", function () {
        spyOn(object, "by_id").andReturn("THE_QUESTION");

        routeParams["id"] = "QUESTION_ID";

        scope.init();

        expect(object.by_id).toHaveBeenCalledWith("QUESTION_ID");
        expect(scope.question).toBe("THE_QUESTION");
    });

    it("if SURVEY not defined go to init path", function () {
        object = null;

        var cookies = {
            object_id: "OBJECT_ID",
            param1: "VALUE1"
        }

        spyOn($, "cookie").andReturn(JSON.stringify(cookies));

        scope.init();

        expect(location.url()).toBe("/path");
        expect($.cookie).toHaveBeenCalledWith("stored_params");
    });


});

以下是错误消息:

Chrome 33.0.1750 (Mac OS X 10.9.2) Controller: ctrl load the proper question FAILED
TypeError: Object THE_QUESTION has no method 'answered'

0 个答案:

没有答案