模拟Redis,但找不到结果

Mock Redis, but can not find the result

提问人:Ken Chang 提问时间:11/7/2023 更新时间:11/7/2023 访问量:18

问:

我目前正在使用 mocha.js、sinon.js 和 chai.js 进行单元测试。 测试时,我模拟redis到createClient。

这是我要测试的代码:

async setAsync(key, value, ttl) {
    return await redisClient.setAsync(key, value).then((reply) => {
      consoleLogger.log(`redisClient set key[${key}] reply=${reply}`);
      console.log('RedisClient:', redisClient);

      if (ttl) {
        return redisClient.expireAsync(key, ttl).then(() => {
          return Promise.resolve();
        });
      }
      return Promise.resolve();
    });
  }

这是我的单元测试:

sinon.stub(redis, 'createClient').returns({
  exists: function () {},
  set: function (key, value, cb) {
    console.log(`mocked set, request: ${key} -> ${value}`);
    return cb(null, 'OK');
  },
  setAsync: async function (key, value, ttl) {
    console.log(`mocked setAsync, request: ${key} -> ${value} -> ${ttl} `);

    if (ttl) {
      await sleep(100);
      return 'OK';
    } else {
      return 'OK';
    }
  },
  expireAsync: async function (key, ttl) {
    console.log(`mocked expireAsync, request: ${key} -> ${ttl}`);
    return 1;
  },
});



describe('redisDao', () => {
  afterEach(() => {
    sandbox.restore();
  });

  it('should set a key in Redis', async () => {
    const key = 'testKey';
    const value = 'testValue';
    const ttl = 3600;

    const redisDAO = new RedisDao();
    const result = await redisDAO.setAsync(key, value, ttl);

    console.log('----');
    console.log(result); 
    console.log('----');
    expect(result).to.equal('OK');
  });
 
 
});

这是,当我运行时:console.log('RedisClient:', redisClient)npm run test

RedisClient: {
  exists: [Function: exists],
  set: [Function: set],
  setAsync: [Function: ret],
  expireAsync: [AsyncFunction: expireAsync],
    
    .....
    .....
}

单元测试错误:

1) redisDao should set a key in Redis:
     AssertionError: expected undefined to equal 'OK'
      at Context.<anonymous> (test/unit/testRedisDAO.js:63:23)

我不明白为什么 RedisClient 只获得 expireAsync,而 setAsync 却没有。有人可以回答我吗?谢谢。

JavaScript 单元测试 Redis Mocha.js sinon

评论


答: 暂无答案