简体   繁体   中英

Jasmine.js How to unit test a function that is calling an undefined function?

My function getLink(rel) calls a function that does not exist in the testing environment.

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 does not exist and I wouldn't want to test it as I want to isolate the object I am currently testing. How would I spy this function (or stub it, whatever is the thing to do, but I think it's stub) with Jasmine 2.0?

You can call your function in context of spy object using call method. It will look something like this:

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(){
    ...
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM