Reputation: 3
It's my code written in Typescript;
I want to test the private getFunc
method and the method of redisClient
have been called Once.
I use supertest to invoke the API, but I can't expect the redis method.
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
Help me, how do I properly stub the redisClient.get(...) function?
Upvotes: 0
Views: 298
Reputation: 762
First of all, you don't usually test dependencies/dependency methods. You only test your code.
Secondly, I think you're saying you want want to check if redis.get()
is being called or not. That means you'll have to spy
on it.
jest.spyOn()
is something you should check out.
Your test should look something like:
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();
});
});
Or something similar, I don't know if this code will work as is. But, you're always welcome to try.
Upvotes: 1