javascript - 带有返回函数和 sinon 的存根函数?
问题描述
我想进行单元测试并覆盖我的代码,这是我的代码,如何用 sinon 覆盖 createClient ?
const client = redis.createClient({
retry_strategy: function(options) {
if (options.error) {
if (options.error.code === 'ECONNREFUSED') {
return new Error('The server refused the connection');
}
if (options.error.code === 'ECONNRESET') {
return new Error('The server reset the connection');
}
if (options.error.code === 'ETIMEDOUT') {
return new Error('The server timeouted the connection');
}
}
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error('Retry time exhausted');
}
if (options.attempt > 10) {
return undefined;
}
return Math.min(options.attempt * 100, 3000);
}
解决方案
您可以做的另一种方法是使用proxyquire模拟redis.createClient
返回,opt
以便我们可以访问retry_strategy
. 在测试中,我们调用retry_strategy
并通过它的options
// test.js
const proxyquire = require('proxyquire');
const src = proxyquire('./your-source-file', { 'redis': { createClient(opt) {
return opt
}}});
const chai = require('chai');
const expect = chai.expect;
describe('testing redis ', function() {
it('refuses connection', function() {
const options = {
error: {
code: 'ECONNREFUSED'
}
}
expect(src.retry_strategy(options).message).to.equal('The server refused the connection');
});
});
这是我用于测试的源文件
// source.js
const redis = require('redis');
const client = redis.createClient({
retry_strategy: function(options) {
if (options.error) {
if (options.error.code === 'ECONNREFUSED') {
return new Error('The server refused the connection');
}
if (options.error.code === 'ECONNRESET') {
return new Error('The server reset the connection');
}
if (options.error.code === 'ETIMEDOUT') {
return new Error('The server timeouted the connection');
}
}
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error('Retry time exhausted');
}
if (options.attempt > 10) {
return undefined;
}
return Math.min(options.attempt * 100, 3000);
}
});
module.exports = client;
推荐阅读
- java - 首次创建数据库时,休眠初始数据导入不起作用
- python - 如何获取 csv 列的名称以避免写入 "key1": row [1], "key2": row [2]
- angular - Angular 指令无法在浏览器中加载/不起作用
- c++ - 移动构造函数和移动赋值。基类中的运算符
- python - 在 Python 中使用 Confluent Kafka Consumer
- kubernetes - 使用 init-container 更改 PV 权限时权限被拒绝
- python-3.x - 如何使用 Flask-WTF 表单实现日期选择器
- python - 您可以仅将一些子图复制到新图形吗?
- typescript - 调试 Jest 测试 Visual Studio 代码
- php - Laravel Carbon 更改时间,但不更改基于时区的日期