Markus
Markus

Reputation: 177

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. If mock those external ones, than Istanbul doesn't count those lines as covered.

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.

Upvotes: 1

Views: 4711

Answers (1)

kasperoo
kasperoo

Reputation: 1584

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

e.g. 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);
  });
});

Upvotes: 1

Related Questions