简体   繁体   English

使用Jasmine中的外部库进行单元测试

[英]Unit testing with external library in Jasmine

How to unit test your code if it's heavily belongs to external library and within each of its methods it calls some external library function. 如果代码很大程度上属于外部库,并且如何在其每个方法内调用单元外部库函数,则如何对其进行单元测试。 If everything to mock, than code coverage like Istanbul don't count those lines mocked. 如果要嘲笑一切,那么像伊斯坦布尔这样的代码覆盖范围就不包括那些被嘲笑的行。 Who has experience in unit testing with involvement of external dependencies and libraries, what is the best practice? 谁在涉及外部依赖项和库的单元测试方面有经验,最佳实践是什么?

For instance, we have 2 internal functions and 3 external library functions. 例如,我们有2个内部函数和3个外部库函数。 If mock those external ones, than Istanbul doesn't count those lines as covered. 如果模拟那些外部行,那么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;
}

How to write a test for internalFoo1() so unit test will cover all its code lines, as well internalFoo2() one. 如何为internalFoo1()编写测试,以便单元测试将覆盖其所有代码行以及internalFoo2()。

Ideally you shouldn't be testing external libraries, it's not your job. 理想情况下,您不应该测试外部库,这不是您的工作。

In this case, you could just use a spy and see if that library has been called. 在这种情况下,您可以只使用一个间谍程序,看看该库是否已被调用。 http://jasmine.github.io/2.2/introduction.html#section-Spies http://jasmine.github.io/2.2/introduction.html#section-Spies

eg taken from Jasmine documentation: 例如摘自茉莉花文档:

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);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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