用sinon和bluebird来保存一个promisifiedfunction
在我想testing的文件中,我有以下代码:
var httpGet = Promise.promisify(require("request").get); httpGet(endpoint, { auth: {bearer: req.body.access_token}, json: true }) .then(...)
现在,在我的testing中,我想确保httpGet被调用一次,并确保参数是有效的。 在promisified之前,我的testing看起来是这样的:
beforeEach(function () { request.get = sinon.stub() .yields(null, null, {error: "test error", error_description: "fake google error."}); }); afterEach(function () { expect(request.get).to.have.been.calledOnce(); var requestArgs = request.get.args[0]; var uri = requestArgs[0]; expect(uri).to.equal(endpoint); //... });
不幸的是,当request.get被promisified时,这不再起作用。 我尝试刷新request.getAsync而不是(因为蓝鸟附加“asynchronous”promisifiedfunction),但是这也不起作用。 有任何想法吗?
Promise.promisify不修改对象,它仅仅是一个函数,并返回一个新的函数,它完全不知道该函数甚至属于"request"
。
当使用promisify All时, "Async"
后缀方法被添加到对象
Promise.promisifyAll(require("request")); request.getAsync = sinon.stub() .yields(null, null, {error: "test error", error_description: "fake google error."}); expect(request.getAsync).to.have.been.calledOnce();
任何人都碰到这个。 我有小工具func
function stubCBForPromisify(stub) { let cbFn = function() { let args = [...arguments]; args.shift(); return stub(...args); }; return cbFn.bind(cbFn, () => ({})); }
在testing中
var getStub = sinon.stub().yields(null, {error: "test error", error_description: "fake google error."}) sinon.stub(require("request"), 'get', stubCBForPromisify(getStub)) expect(getStub).to.have.been.calledOnce();
我遇到麻烦testing这个使用tape
和proxyquire
。 我不确定人们正在使用什么模式/框架,允许他们直接修改required
的request
对象,如接受的答案中所示。 在我的情况下,我想要testing的文件require('jsonFile')
,然后调用bluebird.promisifyAll(jsonFile)
。 在正常情况下,这将创build一个我想存根的readFileAsync
方法。 但是,如果在testing期间我尝试使用proxyquire
传递一个存根,调用promisifyAll
覆盖我的存根。
我能够通过promisifyAll
来解决这个问题。 如图所示,如果依靠一些asynchronous方法来创build,那么这可能太粗糙了。
core.js
:
var jsonFile = require('jsonfile'); var Promise = require('bluebird'); Promise.promisifyAll(jsonFile); exports.getFile = function(path) { // I want to stub this method during tests. It is // created by promisifyAll return jsonFile.readFileAsync(path); }
core-test.js
:
var proxyquire = require('proxyquire'); var tape = require('tape'); var sinon = require('sinon'); require('sinon-as-promised'); tape('stub readFileAsync', function(t) { var core = proxyquire('./core', { 'jsonfile': { readFileAsync: sinon.stub().resolves({}) }, 'bluebird': { promisifyAll: function() {} } }); // Now core.getFile() will use my stubbed function, and it // won't be overwritten by promisifyAll. });