【问题标题】:Angular Jasmine - mock service (angularjs-rails-resource) - TypeError: object is not a functionAngular Jasmine - 模拟服务(angularjs-rails-resource) - TypeError:对象不是函数
【发布时间】:2014-05-21 07:01:35
【问题描述】:

这是带有 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"])

有人可以帮忙吗? :-)

【问题讨论】:

    标签: javascript angularjs unit-testing mocking jasmine


    【解决方案1】:

    我相信错误是在这一行引发的:

    $scope.appointment = new Appointment();
    

    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"])
    }
    

    【讨论】:

    【解决方案2】:

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

    我有一个建议可以让你的描述块看起来更干净 模块和注入语句可以嵌套在 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"])
                }
            });
        }));
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多