在 Jest 中,模拟在测试函数中实例化的 class 的构造函数
In Jest, mock the constructor of a class instantiated in the tested function
我想测试getSessionStorage()
。
在 getSessionStorage()
内,我正在呼叫 new RedisStore(process.env.REDIS_URL)
。
这会引发错误,因为 process.env.REDIS_URL 在 vpn 之外无法访问。
如何模拟 RedisStore.constructor 以避免调用 this.client.connect();
从而避免错误?
RedisStore.js
import { createClient } from "redis";
class RedisStore {
/**
* @param {string} url
*/
constructor(url) {
this.client = createClient({ url });
this.client.on("error", (err) => console.log("Redis Client Error", err));
this.client.connect();
}
async storeCallback(session) {}
async loadCallback(id) {}
async deleteCallback(id) {}
}
export default RedisStore;
getSessionStorage.js
import RedisStore from "./RedisStore";
const getSessionStorage = ()=> {
return new RedisStore(process.env.REDIS_URL);
}
export default getSessionStorage;
getSessionStorage.test.js
import getSessionStorage from "./getSessionStorage.js";
describe("getSessionStorage", () => {
it("should pass", () => {
expect(getSessionStorage()).toMatchObject({
storeCallback: expect.any(Function),
loadCallback: expect.any(Function),
deleteCallback: expect.any(Function)
});
});
});
你可以模拟redis:
jest.mock('redis', () => ({
createClient : jest.fn().mockReturnValue({
on: jest.fn(),
connect: jest.fn()
}),
}));
我想测试getSessionStorage()
。
在 getSessionStorage()
内,我正在呼叫 new RedisStore(process.env.REDIS_URL)
。
这会引发错误,因为 process.env.REDIS_URL 在 vpn 之外无法访问。
如何模拟 RedisStore.constructor 以避免调用 this.client.connect();
从而避免错误?
RedisStore.js
import { createClient } from "redis";
class RedisStore {
/**
* @param {string} url
*/
constructor(url) {
this.client = createClient({ url });
this.client.on("error", (err) => console.log("Redis Client Error", err));
this.client.connect();
}
async storeCallback(session) {}
async loadCallback(id) {}
async deleteCallback(id) {}
}
export default RedisStore;
getSessionStorage.js
import RedisStore from "./RedisStore";
const getSessionStorage = ()=> {
return new RedisStore(process.env.REDIS_URL);
}
export default getSessionStorage;
getSessionStorage.test.js
import getSessionStorage from "./getSessionStorage.js";
describe("getSessionStorage", () => {
it("should pass", () => {
expect(getSessionStorage()).toMatchObject({
storeCallback: expect.any(Function),
loadCallback: expect.any(Function),
deleteCallback: expect.any(Function)
});
});
});
你可以模拟redis:
jest.mock('redis', () => ({
createClient : jest.fn().mockReturnValue({
on: jest.fn(),
connect: jest.fn()
}),
}));