redis"/>
使用 redis
我正在尝试连接到 redis 并使用 node-typescript 中的 redis-mock 库在 redis 中设置数据,但测试失败
redis连接代码:
let client: RedisClientType;
client = createClient({
url: "redis://localhost:6379",
});
beforeAll(() => {
async () => {
try {
await client.connect();
} catch (error) {
console.error('Error connecting redis');
}
};
});
我已经根据
redis-mock
文档在 jest.config.js 文件中配置了 redis-mock,但不知何故它不起作用
这里是测试用例:
describe('Redis', () => {
it('should set user info in Redis', async () => {
const userInfo = { id: 1, name: 'John Doe' };
const token = 'some-token';
await client.set(token, JSON.stringify(userInfo));
const result = await client.get(token);
expect(result).toEqual(JSON.stringify(userInfo));
});
});
redis set方法的返回值返回undefined
回答如下:redis-mock get & set 方法需要一个回调函数。 看这里的例子:https://github/yeahoffline/redis-mock/blob/master/test/client/redis-mock.set.test.js#L517
jest.mock('redis', () => jest.requireActual('redis-mock'));
const redis = require( 'redis' );
const client = redis.createClient();
describe( 'Redis', () => {
it( 'should set user info in Redis', ( done ) => {
const userInfo = { id: 1, name: 'John Doe' };
const token = 'some-token';
client.set( token, JSON.stringify( userInfo ), () => {
client.get( token, ( err, result ) => {
expect( result ).toEqual( JSON.stringify( userInfo ) );
done();
} );
} );
} );
} );
更多推荐
使用 redis
发布评论