如果代码很大程度上属于外部库并且在其每个方法中调用一些外部库函数,则如何对代码进行单元测试。 如果要模拟所有内容,那么像 Istanbul 尔这样的代码覆盖率就不会计算被模拟的那些行。谁有涉及外部依赖项和库的单元测试经验,最佳实践是什么?
例如,我们有 2 个内部函数和 3 个外部库函数。 如果模拟那些外部的,那么 Istanbul 尔不会将这些行算作覆盖。
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()代码行。
最佳答案
理想情况下,您不应该测试外部库,这不是您的工作。
在这种情况下,您可以使用 spy 来查看该库是否已被调用。 http://jasmine.github.io/2.2/introduction.html#section-Spies
例如摘自 Jasmine 文档:
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);
});
});
关于javascript - Jasmine 中使用外部库进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36956210/