首页 > 解决方案 > 我如何对依赖方法进行单元测试

问题描述

这是我用 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"));
    }
}

错误:未捕获的 AssertionError:预期 get 只被调用了一次,但它被调用了 0 次

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

标签: node.jsunit-testingsinon

解决方案


首先,您通常不会测试依赖项/依赖项方法。你只测试你的代码。

其次,我认为你是说你想检查是否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();
  });
});

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


推荐阅读