我想进行单元测试并覆盖我的代码,这是我的代码,如何用 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);
}
最佳答案
测试分配给 retry_strategy
的函数的最简单方法是将其移出 redis.createClient
调用并将其导出:
export const retryStrategy = 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);
}
const client = redis.createClient({
retry_strategy: retryStrategy
...
然后就可以导入直接测试了:
import { retryStrategy } from './your-module';
test('retryStrategy', () => {
expect(retryStrategy({ attempt: 5 })).toBe(500); // SUCCESS
...
})
关于javascript - 带有 sinon 返回函数的 stub 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54971455/