【问题标题】:How to mock Bugsnag in jest test cases for a react app如何在反应应用的开玩笑测试用例中模拟 Bugsnag
【发布时间】:2021-12-29 22:21:55
【问题描述】:
Bugsnag.start({
  apiKey: BUGSNAG_KEY,
  plugins: [new BugsnagPluginReact()],
  releaseStage: process.env.NODE_ENV,
  appVersion: APP_VERSION,
})

const ErrorBoundary = Bugsnag.getPlugin('react').createErrorBoundary(React)

使用“@bugsnag/js”:“^7.11.0”,“@bugsnag/plugin-react”:“^7.11.0”,

试图做 jest.mock("@bugsnag/js") 但得到错误 TypeError:无法读取未定义的属性“createErrorBoundary”

【问题讨论】:

  • 显示测试代码。另外,请提供完整、最少的代码
  • 您可能不应该模拟 Bugsnag - 这是您不拥有的 API。根据您要测试的内容以及边界所在的位置,您可能希望将其封装在例如您拥有的一个函数(并且您可以轻松地模拟)或简单地对没有错误边界的组件进行单元测试(然后进行集成级测试,以确保错误边界自身的行为是适当的)。
  • 在 GitHub 上的 bugsnag-js 存储库中有一个关于问题之一的对话,讨论了如何在测试中处理 Bugsnag 和 ErrorBoundary 组件:github.com/bugsnag/bugsnag-js/issues/344#issuecomment-386156305。可能值得回顾一下,看看你的进展如何?

标签: reactjs jestjs bugsnag


【解决方案1】:

下面是一个如何让这个工作的例子:

jest.mock('bugsnag-js', () => (
  () => ({
    use(plugin) {
      const boundary = plugin.init();
      /* you don't want the error boundary to swallow the errors, 
         just want jest to see them and fail the test
      */
      delete boundary.prototype.componentDidCatch;
      return boundary;
    },
  })
));

【讨论】:

    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2019-06-14
    • 2014-09-18
    • 1970-01-01
    • 2021-06-16
    • 2020-03-02
    相关资源
    最近更新 更多