使用 redis

编程入门 行业动态 更新时间:2024-10-05 13:21:30

使用 <a href=https://www.elefans.com/category/jswz/34/1771249.html style=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

本文发布于:2024-05-30 20:01:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770867.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!