javascript - Angular Jasmine - 模拟服务(angularjs-rails-resource) - TypeError : object is not a function

标签 javascript angularjs unit-testing mocking jasmine

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

我有简单的 Controller :

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

有人可以帮忙吗? :-)

最佳答案

我相信错误是在这一行抛出的:

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

关于javascript - Angular Jasmine - 模拟服务(angularjs-rails-resource) - TypeError : object is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22939468/

相关文章:

java - 对 REST 端点进行单元测试的最佳方法是什么( Jersey )

java - 坑突变 - if ( x !=null ) return null else throw new RuntimeException

javascript - 使 postMessage() 和 addEventListener() 与 IE8 兼容

javascript - 如何在javascript中将整数转换为短整数

angularjs - 为Angular html5mode配置Webpack开发服务器

android - 创建新 Ionic 项目时运行子过程电容器时发生错误

javascript - 无法在 AngularJS 中注册模块

php - 您将如何测试使用全局变量的 PHP 代码?

javascript - 适用于桌面的类似 jsPerf 的应用程序

javascript - 适用于 google chrome,但不适用于 firefox 和 IE