首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJs单元测试-被嘲笑的承诺不执行“那么”

AngularJs单元测试-被嘲笑的承诺不执行“那么”
EN

Stack Overflow用户
提问于 2013-09-20 12:04:18
回答 1查看 4.4K关注 0票数 11

我们正在对控制器进行测试。我们成功地模拟了对REST服务层的调用,并验证了它确实是用给定的数据调用的。但是,现在我们想测试一下,在控制器中,then承诺的执行改变了location.path

主计长:

代码语言:javascript
复制
(function () {

    app.controller('registerController', ['$scope', '$location', '$ourRestWrapper', function ($scope, $location, $ourRestWrapper) {

    $scope.submitReg = function(){
        // test will execute this
        var promise = $ourRestWrapper.post('user/registration', $scope.register);

        promise.then(function(response) {    
                console.log("success!"); // test never hits here           
                $location.path("/");
        },
            function(error) {
                console.log("error!"); // test never hits here
                $location.path("/error");
            }
        );
    };

$ourRestWrapper.post(url,data)刚刚包装Restangular.all(url).post(data)..。

我们的测试:

代码语言:javascript
复制
(function () {

    describe("controller: registerController", function() {

        var scope, location, restMock, controller, q, deferred;

        beforeEach(module("ourModule"));

        beforeEach(function() {
            restMock = {
                post: function(url, model) {
                    console.log("deferring...");
                    deferred = q.defer();    
                    return deferred.promise;
                }
            };
        });

        // init controller for test
        beforeEach(inject(function($controller, $rootScope, $ourRestWrapper, $location, $q){
            scope = $rootScope.$new();
            location = $location;
            q = $q;

            controller = $controller('registerController', {
                $scope: scope, $location: location, $ourRestWrapper: restMock});
        }));

    it('should call REST layer with registration request', function() {
        scope.register = {data:'test'};

        spyOn(restMock, 'post').andCallThrough();

        scope.submitReg();

        deferred.resolve();

        // successfull
        expect(restMock.post).toHaveBeenCalledWith('user/registration',scope.register);
        expect(restMock.post.calls.length).toEqual(1);
        // fail: Expected '' to be '/'.
        expect(location.path()).toBe('/');
    });

在我们的控制台里,我们看到“推迟.”前两种期望都成功了。为什么不调用then块(即设置位置)?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-20 14:34:37

从注入器获取$rootscope对象时缓存它,并在deferred.resolve()之后立即调用$rootScope.$apply()

票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18916348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档