姬長信(Redy)

javascript-模拟服务返回promise:无法读取未定…


我正在使用Karma和Jasmine进行单元测试.我将app.js作为主要源文件:

app.service("someServ", function(){
  this.sendMsg = function(name){
    return "Hello " + name;
  }
})

app.factory("appFactory", function ($q, someServ) {
  function getData() {
    var defer = $q.defer();
    defer.resolve("Success message");
    return defer.promise;
} 

function foo(){
    var text = someServ.sendMsg("Message");
    alert(text);
}
return {
    getData : getData,
    foo : foo
}
})

app.controller("mainController",['$scope','$http','appFactory',function($scope, $http, appFactory){
var mct = this;
mct.printData = function(){
    var myPromise = appFactory.getData();
    myPromise
        .then(function(data){
            alert("Promise returned successfully. Data : " + data);
        }, function(error){
            alert("Something went wrong.... Error: "  + error);
        })
}
mct.showMsg = function(){
    appFactory.foo();
}
}]);

我的testFile.js如下:

   beforeEach(module(function($provide){
    $provide.service("someServ", function(){
        this.sendMsg =   jasmine.createSpy('sendMsg').and.callFake(function(param){})
    });

    $provide.factory("appFactory", function(someServ, $q){
        function getData(){
            var defer = $q.defer();
            defer.resolve("Success message");
            return defer.promise;
        }
        function foo(){
            var facParam = "some text";
            someServ.sendMsg(facParam);
        }
        return {
            getData : getData,
            foo : foo
        }
    });
}));

var $scope, mainController, appFactoryMock, someServMock;

beforeEach(inject(function($rootScope, $controller, $http, $q, appFactory, someServ){
    appFactoryMock = appFactory;
    someServMock = someServ;
    $scope = $rootScope.$new();
    mainController = $controller("mainController", {
        $scope : $scope,
        $http : $http,
        appFactory : appFactoryMock
    });

}));

it('that mainController is calling appFactory methods', function(){
    spyOn(appFactoryMock, "getData");
    mainController.printData();
    scope.$root.$digest();
    expect(appFactoryMock.getData).toHaveBeenCalled();
})

it('that appFactory method foo calls someServ sendMsg', function(){
    spyOn(appFactoryMock, "foo");
    appFactoryMock.foo();
    expect(someServMock.sendMsg).toHaveBeenCalled();
});

以上两个测试均失败.对于第一个,错误是:无法读取未定义的属性,对于第二个:错误:预期的间谍sendMsg已被调用.第一个错误发生在:app.js文件,如调用堆栈中所示.我还使用karma chrome窗口中的Debug选项调试了测试. printData()函数正在app.js中调用实际代码,但我已经对其进行了模拟.

请任何人解释我为什么会这样以及如何解决这个问题?为什么要调用原始代码,以及如何使这两个测试通过?