最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用 redis

网站源码admin38浏览0评论

使用 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();
         } );
      } );
   } );
} );

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论