[英]Stub function with return function with 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);
}
測試分配給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
...
})
您可以執行的另一種方法是使用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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.