【问题标题】:Testing a service call to Restangular with nested spy使用嵌套间谍测试对 Restangular 的服务调用
【发布时间】:2014-01-29 17:52:45
【问题描述】:

我正在测试的服务有这个功能(例如):

doSomething : function(userID,boolean){

                var t = otherService.getSomething();
                var params = somedata;
                var deferred = $q.defer();
                if (boolean){
                    Restangular.one("users",userID).post("copy",params).then(function(data){...

我只是想在 Restangular 上做一个间谍,看看它是否获得了正确的参数、端点等来使用。

所以我做了一个restangular mock:

mockRestangular = {
                    one:function(){return this}
                    },



                    post:function(){

                    },
                    all:function(){

                    }
                };
                    },

//also tried:
// one: function(){return {post:function(){}};}


                };

但我无法在模拟中的嵌套帖子上设置茉莉花间谍:

spyOn(mockRestangular.one,'post')我得到post() method does not exist

函数调用也失败了

someService.doSomething(params)

因为它可以找到 post 方法。

请注意,我需要将 post 方法嵌套到 one 方法中。如果我只是把一个变成一个对象,它会因为缺少 one 方法而失败。

我猜我遗漏了一些明显的东西,但我整个早上都在思考这个问题并且完全失败了

编辑:

andCallThrough() 添加到间谍中使所有部分都朝着正确的方向解决。如果有一天有人会来看,我会更新答案。

【问题讨论】:

  • 模拟注入在哪里?你认为你可以创建一个 plunker 吗?
  • 感谢您的帮助,但我只是想通了,当我将andCallThrough() 与间谍一起使用时,一切都开始朝着正确的方向发展。不是很直观,至少对我而言

标签: angularjs jasmine restangular


【解决方案1】:

解决方案是: 添加到第一个间谍:

spyOn(mockRestangular,'one').andCallThrough();

并将对象更改为:

mockRestangular = {
                    one:function(){
                         return this //since this can be chained to another one or post method, this way it always has one...
                    },



                    post:function(){

                    },
                    all:function(){

                    }
                };

编辑:我搬到诗乃,反正茉莉间谍太有限了。

编辑:这是在 karma/jasmine 测试中转移到 chai+sinon 的方法(不转移到 mocha..):

npm install karma-sinon-chai

添加到 karma.conf.js:

将其添加到plugins 列表中

'karma-sinon-chai'

并改变框架:

    frameworks: ['jasmine','sinon-chai'],

现在在 karma.conf 文件的 files 数组中添加一个 chai-helper.js 文件(名称无关紧要)。

文件应包括:

var should = chai.should(); //you don't need all three, just the style you prefer.. 
var expect = chai.expect; //notice that using would break existing test and need you to do a little rewrite to fix the matchers. if you don't want to, comment this line out
var assert = chai.assert;

【讨论】:

  • 愿意分享解决方案吗?
  • @TomažZaman 使用 sinon 和 chai 的设置说明编辑了答案。虽然这确实可以通过模拟 allone 返回 this 并允许 Restangular 链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多