簡體   English   中英

使用Jasmine中的外部庫進行單元測試

[英]Unit testing with external library in Jasmine

如果代碼很大程度上屬於外部庫,並且如何在其每個方法內調用單元外部庫函數,則如何對其進行單元測試。 如果要嘲笑一切,那么像伊斯坦布爾這樣的代碼覆蓋范圍就不包括那些被嘲笑的行。 誰在涉及外部依賴項和庫的單元測試方面有經驗,最佳實踐是什么?

例如,我們有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()。

理想情況下,您不應該測試外部庫,這不是您的工作。

在這種情況下,您可以只使用一個間諜程序,看看該庫是否已被調用。 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);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM