【问题标题】:Global variable mocking in jest开玩笑的全局变量模拟
【发布时间】:2020-07-21 22:12:18
【问题描述】:

在过去的几个小时里,我一直在为开玩笑测试中的一个错误而苦苦挣扎。全局变量不会让我测试我的组件。我尝试以多种方式模拟变量,但没有任何效果。我尝试在 package.json 中将“全局”属性添加到我的 jest 配置中(没有 ork)。我尝试在我的测试文件中模拟变量(没有用)。有人可以帮我看看吗?

这是我遇到的错误

  ● Test suite failed to run

    TypeError: Cannot read property 'raven_dsn' of undefined

      20 |         }
      21 |     }
    > 22 |     setExtraContext(extraContex){
      23 |         if (global.context.raven_dsn) {
      24 |             Raven.setExtraContext(extraContex);
      25 |         }

      at new Logger (realistico/frontend/react/libraries/Logger.js:22:28)
      at Object.<anonymous> (realistico/frontend/react/libraries/Track.js:14:14)
      at Object.<anonymous> (realistico/realpano/react/components/Viewer.jsx:35:14)
      at Object.<anonymous> (realistico/newcms/react/components/StartView.js:19:15)
      at Object.<anonymous> (realistico/newcms/react/components/ViewManager.js:26:18)
      at Object.<anonymous> (realistico/newcms/react/components/HouseDetail.js:36:20)
      at Object.<anonymous> (__tests__/House.test.js:27:20)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.112s
Ran all test suites.

这就是我实际可以模拟的全局变量的样子

(global).gettext = jest.fn(); // ==> DOES WORK
(global).window.context = jest.fn(); // ==> DOES WORK
(global).onAddhouse = jest.fn(); // ==> DOES WORK
(global).context = jest.fn(() => {});  // ==> DOESN'T WORK

【问题讨论】:

  • 你能提供一个最小的、完整的、可重现的代码吗?

标签: reactjs mocking jestjs


【解决方案1】:

如果全局 context 是一个对象,您应该尝试在测试中将其初始化为一个对象:

global.context = {};

请注意,如果您希望raven_dsn 属性具有特定值,您还必须定义它:

global.context = {
    raven_dsn: 'raven_dsn_value'
};

【讨论】:

  • 已经试过了,也没用。这让我发疯了,所以我就走了简单的路
【解决方案2】:

我无法以“正确”的方式解决它。我只是在该特定函数中添加了一个 if 语句,它就成功了。

if (global.context && global.context.raven_dsn) {
     Raven.setExtraContext(extraContex);
}

【讨论】:

    猜你喜欢
    • 2022-12-24
    • 1970-01-01
    • 2023-02-03
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多