【问题标题】:In jest I can't access to my exported module开玩笑说我无法访问我导出的模块
【发布时间】:2022-02-10 19:18:02
【问题描述】:

比如我无法访问这个模块,为什么?

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);
    },
};

当我运行这个测试时,我得到这个: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);
        }
 });

【问题讨论】:

  • 除了您向我们展示的内容之外,您的测试不包含其他内容?
  • @AhmadMOUSSA 真正的问题是为什么我的导出模块无法访问开玩笑测试?
  • 您的问题是“为什么您的导出模块无法访问 jest 测试”或“为什么您的导出模块无法从 jest 测试中访问”?

标签: javascript testing jestjs nodes ts-jest


【解决方案1】:

这很正常!

实际上,您可以访问您的模块,并且错误进入您的模块,其中“nodeCacheClient”未定义,因为它没有定义!

您的错误来自您的“getCache()”函数,语法如下:

return nodeCacheClient.get(key);

在您的测试中,您没有调用“initNodeCache()”方法,但会这样做

nodeCacheClient = new NodeCache();

因此,对于您的测试范围,nodeCacheClientundefined,这就是为什么

nodeCacheClient.get(key);

将返回

typeError: Cannot read property 'get' of undefined Error

【讨论】:

  • 当服务器准备好监听时,我在 server.js 中执行此操作 app.listen(PORT, () => { getCacheClient.initNodeCache() console.log(Listening on PORT: ${PORT}); })跨度>
  • 通过邮递员,一切都很好:(
  • 邮递员,还是本地环境不像测试环境!
  • 要理解我在说什么,请将 console.log(nodeCacheClient) 放入您的 getCache() 函数中。在 Postman 中,这将记录一些值,但在测试中这将返回“未定义”所以在你的测试中你应该确保 nodeCacheClient 有一个值。
  • 我就是这样做的,如果运气好的话我会尽快重播,谢谢伙计
猜你喜欢
  • 2020-06-11
  • 1970-01-01
  • 2018-03-02
  • 2020-09-17
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多