javascript – AngularJs单元测试 – 嘲笑承诺不执行“那么”

我们对我们的控制器进行单元测试我们已经成功地嘲笑了对我们的REST服务层的调用,并验证了它正在使用给定的数据进行调用.现在我们想测试一下,在我们的控制器中,执行这个承诺会改变location.path:

控制器:

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

我们的测试:

(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,$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('/');
    });

在我们的控制台中,我们看到“推迟…”,前两个预期成功.为什么它不会调用当前块(即设置位置)?

解决方法

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...