JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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().

大佬总结

以上是大佬教程为你收集整理的javascript – AngularJs单元测试 – 嘲笑承诺不执行“那么”全部内容,希望文章能够帮你解决javascript – AngularJs单元测试 – 嘲笑承诺不执行“那么”所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。