'In jest I can't access to my exported module
For example, I can't access to this module, why ?
let nodeCacheClient;
module.exports = {
initNodeCache: () => {
const NodeCache = require("node-cache");
nodeCacheClient = new NodeCache();
return nodeCacheClient;
},
insertToCacheWithTtl: (key, obj, ttl) => {
return nodeCacheClient.set(key, obj, ttl);
},
getCache: (key) => {
return nodeCacheClient.get(key);
},
deleteKey: (key) => {
return nodeCacheClient.del(key);
},
};
when I run this test I get this : TypeError: Cannot read property 'get' of undefined Error
test("login a user", async () => {
try {
const response = await axiosInstance.post("users/login", {
email: "[email protected]",
password: "144847120",
otpCode: getCacheClient.getCache("[email protected]")
});
console.log(response.data);
expect(response.data.status).toBe("success");
} catch (error) {
console.log(error + " Error");
expect(error);
}
});
Solution 1:[1]
It’s totally normal!
Actually you got access to your module, and the error is coming into your module where the “nodeCacheClient” is undefined since it was not defined!
Your error is coming from your “getCache()” function, in this syntax:
return nodeCacheClient.get(key);
Where in your test you didnt call for the “initNodeCache()” method which will do
nodeCacheClient = new NodeCache();
So, for your test scope, the nodeCacheClient is undefined, and that’s why
nodeCacheClient.get(key);
Will return the
typeError: Cannot read property 'get' of undefined Error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmad MOUSSA |
