Angular Jasmine - 模拟服务(angularjs-rails-resource) - TypeError:object不是函数

时间:2014-04-08 14:04:16

标签: javascript angularjs unit-testing mocking jasmine

这是带有angular-rails gem和jasmine gem的Rails 4.0应用程序。我也使用angularjs-rails-resource。

我有简单的控制器:

app.controller('new', function ($scope, Appointment, flash) {

$scope.appointment = new Appointment();
$scope.attachments = [];
$scope.appointment.agendas_attributes = [];

$scope.createAppointment = function(){

    $scope.appointment.attachments = $scope.attachments;

    $scope.appointment.create().then(function(data){
      flash(data.message);
    }, function(error){
      flash('error', error.data.message);
      $scope.appointment.$errors = error.data.errors;
    });

};

在Jasmine的单元测试中,我想用jasmine.createSpyObj隔离依赖项:

describe("Appointment new controller",function() {
var $scope, controller, mockAppointment, mockFlash, newCtrl;


beforeEach(function() {

    module("appointments");

    inject(function(_$rootScope_, $controller) {
      $scope = _$rootScope_.$new();

      $controller("new", {
        $scope: $scope,
        Appointment: jasmine.createSpyObj("Appointment", ["create"])
      });

    });

  });
});

但是我收到了错误:

TypeError: object is not a function

在线:

Appointment: jasmine.createSpyObj("Appointment", ["create"])

有人可以帮忙吗? : - )

2 个答案:

答案 0 :(得分:2)

我相信这条错误正在抛出:

$scope.appointment = new Appointment();

约会是一个对象文字,而不是一个函数,所以基本上你试图这样做:

var x = {create: function(){}};
var y = new x();

但你似乎想要做的是:

var x = function(){return  {create: function(){}}};
var y = new x();

所以让你的模仿这样:

Appointment: function() {
    return jasmine.createSpyObj("Appointment", ["create"])
}

答案 1 :(得分:2)

我看到有人打败了我的答案;)

我有一个建议会让你的描述块看起来更干净 module和inject语句可以嵌套在beforeEach定义中:

describe("Appointment new controller", function () {
    var $scope, controller, mockAppointment, mockFlash, newCtrl;

    beforeEach(module("appointments"));
    beforeEach(inject(function (_$rootScope_, $controller) {
        $scope = _$rootScope_.$new();
        $controller("new", {
            $scope: $scope,
            Appointment: function () {
                return jasmine.createSpyObj("Appointment", ["create"])
            }
        });
    }));
}