How to write mock for a third-party library with nested functions (javascript, jasmine)

I am new to TDD and I am trying to write test code that uses third-party libraries (cross-platform mobile development). I would like to have tests only to test our business logic. Do not worry about their implementation.

Moreover, their libraries are displayed only in their own shells. Since I use js as a development language, I would like to test the use of jasmine and run a test to test my business logic only in a browser.

Here are sample methods that I would like to ignore / layout when testing.

com.companyname.net.checkInternetAvailable(url) 

com.companyname.store.getValue(key)

com.companyname.someother.name(whateverObj, callback) etc.,

At the moment I created a new file mocks.jswhere I just wrote

var com = {
    "net":{},
    "store":{},
    "someother":{}
}

com.net.checkInternetAvailable = function(url){
    //TODO: fix this!
    return true;
}

. Jasmine SpyOn(com.net, "checkInternetAvailable").and.returnValue(true) . , SpyOn.

? ?

+4
1

, , - javacript Sinon, . , , . (SUT) Jasmine.

:

https://jsfiddle.net/Fresh/uf8owzdb/

:

// A module which has methods you want to stub
Net = (function() {

  // Constructor
  function Net() {
  }

  Net.prototype.checkInternetAvailable = function(url) {
    return true;
  };

  return Net;

})();

// A method which is dependent on the Net module
var methodWhichUsesNet = function(net) {
    return net.checkInternetAvailable();
};

// Stub the method behaviour using Sinon javascript framework.
// For the test, get it to return false instead of true.
var net = new Net();
var expectedResult = false;
sinon.stub(net, "checkInternetAvailable").returns(expectedResult);

// Assert method behaviour using a Jasmine test
describe("Net test suite", function() {
  it("methodWhichUsesNet should return expected result", function() {
    expect(methodWhichUsesNet(net)).toBe(expectedResult);
  });
});

, stub , , , , , . mock , , , . , , :

var stub = sinon.stub(obj);

, , , .. , , , .

+4

All Articles