我如何对依赖方法进行单元测试

How can i unit test the dependency method

这是我用 Typescript 编写的代码; 我想测试私有getFunc方法和redisClient方法被调用一次。 我使用 supertest 来调用 API,但我不能期望 redis 方法。

import { Request, Response, Router } from "express";
import * as redis from "redis";
const redisOption: redis.ClientOpts = {
    host: "127.0.0.1",
    port: 6379,
    detect_buffers : true,
    db: 0,
   retry_strategy: () => 60000
}
const redisClient: redis.RedisClient = redis.createClient(redisOption);

export class IndexRoutes {
    public router: Router;
    constructor() {
        this.router = Router();
        this.init();
    }
    public init() {
        this.router.get("/",  this.getFunc);
    }
    private getFunc = async (req: Request, res: Response) => {
        return res.status(200).send(await redisClient.set("test", "123"));
    }
}

error: Uncaught AssertionError: expected get to have been called exactly once, but it was called 0 times

帮帮我,如何正确地存根 redisClient.get(...) 函数?

首先,您通常不会测试 dependencies/dependency 方法。你只测试你的代码。

其次,我想你是说你想检查 redis.get() 是否被调用。这意味着您必须 spy 就可以了。

jest.spyOn() 是您应该查看的内容。

您的测试应该类似于:

import * as redis from 'redis';

describe('my redis wrapper', () => {
  it('Should call get when my wrapper\'s getFunc is called', () => {
    let myRedisSpy = jest.spyOn(redis.prototype, 'get');
    // call your function here
    expect(myRedisSpy).toHaveBeenCalledOnce();
  });
});

或类似的东西,我不知道这段代码是否能按原样工作。但是,随时欢迎您尝试。