testing同步代码
我有一段使用节点同步的代码,如下所示:
function funcA() { return new Promise(function(resolve, reject) { Sync(function () { return funcB.sync(); }, function (err, result) { if(err) { reject(err); } else { resolve(result); } }); }
这段代码使用mocha + chai进行testing:
it("should return array", function() { return funcA().then(function(result) { expect(result).to.be.an.instanceof(Array); }); });
几个月前它工作得很好,但现在这个testing总是超时:
错误:超过2000毫秒超时。 确保在此testing中正在调用done()callback。
我到目前为止所尝试的是:
- 使用
done()
而不是返回一个promise - 用syncize.jsreplace
node-sync
synchronize.js
- 增加超时
我发现的是, expect(...
这个testing的一部分实际上是被调用的,但是只有在mocha杀死testing之后,无论目前设置了什么超时间隔, expect(..
总是被称为〜 20毫秒后我得到Error: timeout
消息。
我通过在testing文件的顶部添加setInterval(function(){}, 10)
来解决这个问题。 我想知道为什么这个工作,如果有更好的方法来解决这个问题?
[编辑]看起来这是一个节点版本的具体问题。 testing在0.12.4上失败,但在0.10.38上正确运行。
[编辑]实际的代码在这里 。
根据你的代码 ,我假设你的funcB函数正在以同步的方式运行代码。
所以当我用这种方式创buildfuncB时:
function funcB() { return [1, 2, 3]; }
并运行testing,摩卡显示一个错误:
错误:超过2000毫秒超时。 确保在此testing中正在调用done()callback。
但是,如果我把这个funcB转换成asynchronous函数 :
function funcB(cb) { process.nextTick(function () { cb(null, [1, 2, 3]); }); }
摩卡运行testing没有任何问题:
✓应该返回一个数组
所以我完整的代码运行正常(funcB评论是会导致错误的)是这样的:
// install dependencies // npm install promise // npm install sync var Promise = require('promise'); var assert = require('assert'); var Sync = require('sync'); function funcA() { return new Promise(function (resolve, reject) { Sync(function () { return funcB.sync(); }, function (err, result) { if (err) { reject(err); } else { resolve(result); } }); }); } // function funcB() { // return [1, 2, 3]; // } function funcB(cb) { process.nextTick(function () { cb(null, [1, 2, 3]); }); } it("should return an array", function(done) { return funcA().then( function (result) { console.log(result); assert.equal(Array.isArray(result), true); done(); } ); });
所以我认为,我认为同步库创build的同步方法 (在同步函数上使用它)的滥用正是导致此问题的原因之一。
你可能会错过done()
callback:
it("should return array", function(done) { funcA().then(function(result) { expect(result).to.be.an.instanceof(Array); done(); }); });
您可以使用mocha可执行文件的超时参数。
例如,如果你想要一个500毫秒的超时,只要把你的package.json
改为:
"scripts": { "test": "mocha specs --timeout 500 --require specs/helpers/chai.js" },
也许你的诺言被拒绝了,所以你必须使用catch
方法来done
。
it("should return array", function(done) { return funcA().then(function(result) { expect(result).to.be.an.instanceof(Array); done(); }).catch(done); });
这也将帮助您debugging您的承诺代码中可能发生的最终错误。