简体   繁体   English

使用sinon对库构造函数进行调用

[英]Stubbing library constructor calls with sinon

Up until now I have been using sinon to stub out function calls on objects included in my nodeJS code. 到目前为止,我一直在使用sinon来对我的nodeJS代码中包含的对象进行函数调用。

For example I use the request library, and so in my tests I can stub out http calls like: 例如,我使用请求库,因此在我的测试中,我可以存根http调用,如:

var request = require('request');
//Somewhere further below in my tests:
postStub = sinon.stub(request, 'post');

I have now hit a scenario where a library I am including needs to be called like so in my actual code: 我现在遇到了一个场景,我需要在我的实际代码中调用我所包含的库:

var archiver = require('archiver');
//Further below in actual code (express middleware)
var zip = archiver('zip');
zip.pipe(res);

I want to be able to stub out calls to pipe() on the archiver library, but I think I need to stub out the constructor call first - archiver('zip') ? 我希望能够在归档库上存根对pipe()调用,但我想我需要先将构造函数调用存根 - archiver('zip')

I have had a search around and I think sinon's createStubInstance could help me here, but I am not 100% sure. 我有一个搜索,我认为sinon的createStubInstance可以帮助我,但我不是100%肯定。

Can someone assist? 有人可以帮忙吗? Thanks 谢谢

It's not pretty but what i've done seems to work. 它不漂亮,但我所做的似乎工作。 Wrap your un-stubbable library function with another exportable method. 使用另一种可导出方法包装不可存根的库函数。

file.js file.js

exports.originalMethod = function() {
  var archiver = require('archiver');
  //Further below in actual code (express middleware)
  var zip = exports.newArchiverMethod('zip');
  zip.pipe(res);
}
exports.newArchiverMethod = function(arg) {
  return archiver(arg);
}

This newArchiverMethod can then be stubbed. 这个newArchiverMethod然后可以被存根。

spec.js spec.js

archiverStub = sinon.stub(controller, 'newArchiverMethod');

It's not perfect because it adds a new exportable method and it creates unnecessary clutter in the original file, as well as a non-testable line. 它并不完美,因为它添加了一个新的可导出方法,它在原始文件中创建了不必要的混乱,以及不可测试的行。 But it does let you get past this one line and test the rest of a long method. 但它确实让你通过这一行并测试其余的长方法。

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

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