如何使用嵌套函数(javascript,jasmine)为第三方库编写模拟

pal*_*aja 5 javascript tdd unit-testing mocking jasmine

我是TDD的新手,我正在尝试编写使用第三方库(跨平台移动开发)的可测试代码.我想测试只是为了检查我们的业务逻辑.不用担心他们的实施.

其他库的更多内容仅在本机包装器中公开.由于使用js作为开发语言,我想使用jasmine进行测试并运行test以仅在浏览器中检查我的业务逻辑.

以下是我想在测试时忽略/模拟的方法模式.

com.companyname.net.checkInternetAvailable(url) 

com.companyname.store.getValue(key)

com.companyname.someother.name(whateverObj, callback) etc.,
Run Code Online (Sandbox Code Playgroud)

目前,我已经创建了一个新mocks.js文件,我只是写了

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

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

我对我代码中的所有方法都这样做.我尝试使用Jasmine SpyOn(com.net, "checkInternetAvailable").and.returnValue(true)而不是定义所有方法.这种方法的问题是我必须定义要使用的所有方法SpyOn.

有更简单的方法吗?推荐的方法是什么?

Ben*_*ith 5

您可以采用的一种方法是使用Sinon javascript测试库来存根第三方库方法.然后可以设置这些存根方法以模拟使用实际第三方库难以再现的结果.然后,您的受测系统(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);
  });
});
Run Code Online (Sandbox Code Playgroud)

请注意,建议将第三方方法存根,因为您要准确控制它们应返回的内容,因为您知道代码正在使用哪些方法.或者,如果您还想验证这些方法是否由使用它们的方法调用,则可以模拟这些第三方方法.您可以使用例如以下方式存根整个第三方对象方法:

var stub = sinon.stub(obj);
Run Code Online (Sandbox Code Playgroud)

但是我建议不要这样做,因为这意味着测试不会那么明确,即你不确定存根方法是如何表现的,而明确地存在它们意味着你可以完全控制它们的行为.