【问题标题】:Test is not running service mock promise (.then)测试未运行服务模拟承诺 (.then)
【发布时间】:2014-05-28 12:49:19
【问题描述】:

我试图创建一个模拟我的BoardService。但是,.then 函数在运行测试时并没有在controller 中运行,但在运行实际应用程序时它工作正常。

这是测试:

beforeEach(inject(function($rootScope, $controller, $q) {

    scope = $rootScope.$new();

    BoardController = $controller('BoardController', {
        $scope: scope,
        board: {
            id: 1,
            tasks: []
        },
        BoardService: {

            addTask: function(data) {
                var defer = $q.defer();
                defer.resolve(1);
                return defer.promise;
            }
        }
    });

}));

it("should add a new task", function() {

    scope.addTask(category, 'this is a new task');

    expect(scope.board.tasks.length).toBe(1);

});

以及控制器功能:

$scope.addTask = function(category, task) {

    BoardService.addTask({name: task, category: category.id, boardId: $scope.board.id}).then(function(task_id) {

        // Never reaches here

        $scope.board.tasks.push({id : task_id, name : task, category : category.id, board_id : $scope.board.id});

    });
}

为什么一直没有到达.then函数中的评论?

【问题讨论】:

    标签: javascript angularjs unit-testing testing jasmine


    【解决方案1】:

    解决承诺后,您需要触发一个摘要循环,以便 Angular 进行处理。

    scope.addTask(category, 'this is a new task');
    scope.$digest();
    expect(scope.board.tasks.length).toBe(1); 
    

    【讨论】:

      【解决方案2】:

      正如我们在 IRC 上讨论的:您需要调用 scope.$digest 才能触发 Promise。

      【讨论】:

        猜你喜欢
        • 2014-05-14
        • 1970-01-01
        • 2016-10-06
        • 2018-05-25
        • 1970-01-01
        • 1970-01-01
        • 2018-07-17
        • 2022-11-13
        • 1970-01-01
        相关资源
        最近更新 更多