2016-04-30 71 views
0

如果单元测试代码严重属于外部库,并且在它的每个方法内调用某个外部库函数,那么该如何进行单元测试。 如果所有事情都是模拟的,而不是像伊斯坦布尔这样的代码覆盖范围,那么这些行就不会被嘲笑。谁拥有涉及外部依赖和图书馆的单元测试经验,最佳实践是什么?在Jasmine中使用外部库进行单元测试

例如,我们有2个内部函数和3个外部库函数。 如果嘲笑那些外部的,比伊斯坦布尔不包括那些线路。

function internalFoo1(input) { 
var result = internalFoo2(input*2); 
var finalResult = externalLibraryBar1(result); 
return result; 
}; 

function internalFoo2(value) { 
    var operation = externalLibraryBar2(value*2); 
    var response = externalLibraryBar3(operation); 
    return response; 
} 

如何写为internalFoo1测试(),因此单元测试将涵盖其所有行代码,以及internalFoo2()之一。

回答

0

理想情况下,你不应该测试外部库,这不是你的工作。

在这种情况下,您可以使用间谍并查看该库是否已被调用。 http://jasmine.github.io/2.2/introduction.html#section-Spies

例如取自茉莉花文件:

describe("A spy, when configured with an alternate implementation", function() { 
    var foo, bar, fetchedBar; 

    beforeEach(function() { 
    foo = { 
     setBar: function(value) { 
     bar = value; 
     }, 
     getBar: function() { 
     return bar; 
     } 
    }; 

    spyOn(foo, "getBar").and.callFake(function() { 
     return 1001; 
    }); 

    foo.setBar(123); 
    fetchedBar = foo.getBar(); 
    }); 

    it("tracks that the spy was called", function() { 
    expect(foo.getBar).toHaveBeenCalled(); 
    }); 

    it("should not affect other functions", function() { 
    expect(bar).toEqual(123); 
    }); 

    it("when called returns the requested value", function() { 
    expect(fetchedBar).toEqual(1001); 
    }); 
});