简体   繁体   English

开个玩笑,我无法访问我导出的模块

[英]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当我运行这个测试时,我得到这个: TypeError: Cannot read property 'get' of undefined Error

test("login a user", async () => {
        try {
            const response = await axiosInstance.post("users/login", {
                email: "test@gmail.com",
                password: "144847120",
                otpCode: getCacheClient.getCache("test@gmail.com")
            });
            console.log(response.data);
            expect(response.data.status).toBe("success");
        } catch (error) {
            console.log(error + " Error");
            expect(error);
        }
 });

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!实际上你可以访问你的模块,错误是进入你的模块,其中“ nodeCacheClient ”是未定义的,因为它没有被定义!

Your error is coming from your “ getCache() ” function, in this syntax:您的错误来自您的“ getCache() ”function,语法如下:

return nodeCacheClient.get(key);

Where in your test you didnt call for the “ initNodeCache() ” method which will do在你的测试中你没有调用“ initNodeCache() ”方法的地方

nodeCacheClient = new NodeCache();

So, for your test scope, the nodeCacheClient is undefined , and that's why因此,对于您的测试 scope, nodeCacheClientundefined ,这就是为什么

nodeCacheClient.get(key);

Will return the将返回

typeError: Cannot read property 'get' of undefined Error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM