node.js - 我如何对依赖方法进行单元测试
问题描述
这是我用 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(...) 函数?
解决方案
首先,您通常不会测试依赖项/依赖项方法。你只测试你的代码。
其次,我认为你是说你想检查是否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();
});
});
或类似的东西,我不知道这段代码是否会按原样工作。但是,随时欢迎您尝试。
推荐阅读
- c# - C# Socket:服务器不发送消息
- java - java.lang.NumberFormatException:调用端口 curl 调用时为 null
- c# - 如何解决 C# 控制台应用程序中的 DLL 劫持问题
- c# - 制作快照并清空 ConcurrentDictionary
- python-3.x - Pandas:从唯一的 multiIndex 数据帧创建不同的数据帧
- flutter - 为什么在运行应用程序时显示端口错误?
- gnuplot - 绘制按天分组的 HTTP 状态代码
- sockets - 如何使用套接字将数据从电子应用程序发送到 Heroku 上的烧瓶应用程序
- unity3d - 检查用户是否已经在 Unity 中通过应用购买中的 google play 购买了商品
- android - 工作管理器的位置更新不起作用