【发布时间】:2021-07-23 13:09:07
【问题描述】:
// client.js
const getCacheClient = async (configuration) => {
return new Promise((resolve, reject) => {
const redisClient = redis.createClient(configuration.port, configuration.host);
// note that promise is fullfiled or rejected based on redis client events
redisClient.on('ready', () => resolve(redisClient));
redisClient.on('error', (redisError) => {
console.log('Error connecting Redis', redisError.message);
redisClient.quitAsync();
return reject(redisError);
});
});
};
测试由 promise 返回但解析或拒绝基于事件处理程序的 Redis 客户端的正确方法是什么?
由于解决或拒绝是基于“成功/错误”事件,我不确定如何重新创建事件。我得到一个 '在 jest.setTimeout.Timeout 指定的 10000 毫秒超时内未调用异步回调 - 在 jest.setTimeout.Error 指定的 10000 毫秒超时内未调用异步回调:'
// client.test.js
import client, { __RewireAPI__ as API } from '../client';
describe('get-cache-client', () => {
const mockBlueprint = { promisifyAll: jest.fn((x) => x) };
const mockRedisClient = {
getAsync: jest.fn(),
setexAsync: jest.fn(),
on: jest.fn(),
};
const mockRedis = {
createClient: {
on: jest.fn(),
},
};
beforeEach(() => {
API.__Rewire__('redis', mockRedis);
API.__Rewire__('blueprint', mockBlueprint);
});
afterEach(() => {
__rewire_reset_all__();
mockRedis.createClient.mockReset();
});
describe('getCacheClient', () => {
it('should create a client with the expected parameters', async (done) => {
const config = {
host: 'testrediscachehost',
port: 1234,
key: 'testrediscachekey',
};
mockRedis.createClient.on.mockReturnValue(mockRedisClient);
const client = await expect(getCacheClient(config));
// it gets stuck here, promise is never fulfilled or rejected
// .... tests...
});
});
});
【问题讨论】:
标签: node.js unit-testing redis jestjs