Javascript js如何对调用未定义函数的函数进行单元测试?
我的函数getLink(rel)调用测试环境中不存在的函数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: 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(){
...
});
});