Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript js如何对调用未定义函数的函数进行单元测试?_Javascript_Unit Testing_Backbone.js_Jasmine_Stub - Fatal编程技术网

Javascript js如何对调用未定义函数的函数进行单元测试?

Javascript js如何对调用未定义函数的函数进行单元测试?,javascript,unit-testing,backbone.js,jasmine,stub,Javascript,Unit Testing,Backbone.js,Jasmine,Stub,我的函数getLink(rel)调用测试环境中不存在的函数 getLink: function(rel) { var schemaLink = null; var schemaLinks = this.collection.getItemSchema().links; schemaLinks.forEach(function(link) { if(link.rel === rel) { schemaLink = link;

我的函数getLink(rel)调用测试环境中不存在的函数

getLink: function(rel) {
    var schemaLink = null;
    var schemaLinks = this.collection.getItemSchema().links;
    schemaLinks.forEach(function(link) {
        if(link.rel === rel) {
            schemaLink = link;
            return false;
        }
    });
    return schemaLink;
},

this.collection不存在,我不想测试它,因为我想隔离当前正在测试的对象。我如何用Jasmine 2.0检测这个函数(或存根函数,无论做什么,但我认为它是存根函数)?

您可以使用方法在spy对象的上下文中调用您的函数。它看起来像这样:

describe('getLink()', function(){
  var result, fooLink, barLink, fakeContext;
  beforeEach(function(){
    fakeContext = {
      collection: jasmine.createSpyObj('collection', ['getItemSchema']);
    };

    fooLink = {rel: 'foo'};
    barLink = {rel: 'bar'};
    fakeContext.collection.getItemSchema.andReturn([fooLink, barLink]);
  });

  desctibe('when schemaLink exists', function(){
    beforeEach(function(){
      result = getLink.call(fakeContext, 'foo')
    });

    it('calls getItemSchame on collection', function(){
      expect(fakeContext.collection.getItemSchame).toHaveBeenCalledWith();
    });

    it('returns fooLink', function(){
      expect(result).toBe(fooLink);
    });
  });

  desctibe('when schemaLink does not exist', function(){
    ...
  });
});