NodeJS Redis mock无法连接

6qfn3psc  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(154)

在jest配置中

setupFilesAfterEnv: ['./libs/redis/test/jest.setup.redis-mock.js'],

jest.setup.redis-mock.js:

jest.mock('redis', () => jest.requireActual('redis-mock'));

基本测试:

import { Redis } from '../../src';

describe('Redis', () => {
  it('test1', async () => {
    const redis = new Redis({ url: 'redis://127.0.0.1:6379' });
    await redis.init();
    expect(1).toBe(1);

    await redis.destroy();
  });
});

还有我的redis Package 纸

import { createClient, RedisClientType } from 'redis';

class Redis {
  private _redis: RedisClientType

  constructor(private _configuration: IRedisConfiguration) {
    this._redisClient = createClient({
      url: this._configuration.url,
      username: this._configuration.userName,
      password: this._configuration.password
    });
  }

  public async init(): Promise<void> {
    await this._redisClient.connect();
  }

  public async destroy(): Promise<void> {
    await this._redisClient.disconnect();
  }
}

当我运行测试时,我得到:

TypeError: this._redisClient.connect is not a function

Redis版本来自npm:4.5.0 redis-mock:0.56.3

编辑

我注解了连接和断开连接函数,现在它不会抛出任何错误,但看起来它不工作。此代码:

await this._redisClient.SADD('myset', 'Hello');
const x = await this._redisClient.SMEMBERS('myset');
console.log('XXX', x);

返回未定义

编辑2

const redismock = require('redis-mock');

(async function() {
  try {
    const client = redismock.createClient();
    await client.sadd('test', 'test');
    const members = await client.smembers('test');
    console.log(members);
  } catch (error) {
    console.error('error', error);
  }
})();

这个简单的代码也返回undefined。我是不是错过了什么东西来正确地嘲笑它?

qojgxg4l

qojgxg4l1#

redis-mock库没有实现redis库的所有方法。例如,未实现.connect().disconnect()。可以检查RedisClient类的源代码中redis-mock.connect().disconnect()方法不存在。这就是为什么要使用TypeError: this._redisClient.connect is not a function
不幸的是,redis-mock库使用错误优先的回调模式实现了redis方法,**没有使用promise。**这就是为什么async/await语法不起作用。
此外,我们应该使用//@ts-nocheck来禁用TypeScript的类型检查,因为redisredis-mock库之间的类型/接口不兼容。它会在编译时导致类型错误。
我们必须使用回调来保证异步代码的执行顺序。
工作示例:
为了访问._redisClient属性,我们需要将其设置为公共属性。
my-redis.ts

import { createClient, RedisClientType } from 'redis';

export class Redis {
    _redisClient: RedisClientType;

    constructor(private _configuration) {
        this._redisClient = createClient({
            url: this._configuration.url,
            username: this._configuration.userName,
            password: this._configuration.password,
        });
    }

    public async init(): Promise<void> {
        await this._redisClient.connect();
    }

    public async destroy(): Promise<void> {
        await this._redisClient.disconnect();
    }
}

my-redis.test.ts

//@ts-nocheck
import { Redis } from './my-redis';

describe('Redis', () => {
    it('test1', (done) => {
        const redis = new Redis({ url: 'redis://127.0.0.1:6379' });
        redis._redisClient.SADD('myset', 'Hello', (err, result) => {
            expect(result).toBe(1);
            redis._redisClient.SMEMBERS('myset', (err, result) => {
                expect(result).toEqual(['Hello']);
                done();
            });
        });
    });
});

测试结果:

PASS  stackoverflow/75926628/my-redis.test.ts
  Redis
    ✓ test1 (3 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.505 s, estimated 2 s

软件包版本:

"redis": "^4.6.7",
"redis-mock": "^0.56.3",

相关问题