AngularJs 单元测试 - 模拟承诺不执行“然后”

AngularJs unit test - mocked promise not executing "then"

本文关键字:执行 然后 承诺 单元测试 模拟 AngularJs      更新时间:2023-09-26

我们正在对控制器进行单元测试。我们已经成功地模拟了对 REST 服务层的调用,并验证了它确实是使用给定数据调用的。但是,现在我们想测试一下,在我们的控制器中,then承诺的执行会改变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, $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块(即设置位置)?

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