作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我只是想知道是否有办法在 mocha 单元测试中模拟“无连接”事件。我有一个返回 promise 的方法,该 promise 应该等待具有轮询策略的互联网连接,我想用 mocha 测试它。有一种方法可以达到这样的结果。
部分代码:
it('should wait for connection', function(done)
{
this.timeout(2500);
//simulate an internet connection drop here
wait.connection().then(done);
setTimeout(//activate connection, 2000);
});
感谢您的任何回复。
[编辑]:这是我要测试的代码:
var wait = {
connection: function()
{
'use strict';
var settings = {retry: 1000};
return new Promise(function(resolve)
{
(function poll()
{
needle.get('https://api.ipify.org', function(error, response)
{
if(!error && response.statusCode === 200 && /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/.test(response.body))
resolve();
else
wait.for(settings.retry).then(poll);
});
})();
});
}
};
在这种情况下,由于新连接可用,Promise 将保持挂起状态。如何在 needle
get 请求上模拟错误?
最佳答案
您可以使用 sinon stub needle.get
var needle = require("needle");
var sinon = require("sinon");;
before(() => {
sinon.stub(needle, "get", (url, calback) => {
var dummyError = {};
callback(dummyError);
})
});
// Run your 'it' here
after(() => {
needle.get.restore();
});
关于node.js - 如何在 Mocha 测试中模拟无连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36948316/
我是一名优秀的程序员,十分优秀!