首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Jest测试Sentry

用Jest测试Sentry
EN

Stack Overflow用户
提问于 2019-05-24 20:10:11
回答 2查看 7.3K关注 0票数 3

我正在测试我的错误边界,以作出反应,并注意到在Codecov中,我的Sentry函数中有一个特定的部分还没有经过测试。

我尝试过使用jest.mock("@sentry/browser")和模仿Sentry,但是,似乎无法测试这些代码。Sentry导入是正确的,但不是scope

下面是我试图嘲弄的一个例子。

代码语言:javascript
复制
import * as Sentry from "@sentry/browser"
const mock_scope = jest.fn(() => {
  return { setExtras: null }
})
Sentry.withScope = jest.fn().mockImplementation(mock_scope)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-25 03:52:26

未测试的行是传递给Sentry.withScope的回调函数。

代码语言:javascript
复制
scope => {
  scope.setExtras(errorInfo);
  Sentry.captureException(error);
}

由于Sentry.withScope已被模拟,您可以使用mockFn.mock.calls检索传递给它的回调函数。

一旦检索了回调函数,就可以直接调用它来测试它。

下面是一个稍微简化的工作示例:

代码语言:javascript
复制
import * as Sentry from '@sentry/browser';

jest.mock('@sentry/browser');  // <= auto-mock @sentry/browser

const componentDidCatch = (error, errorInfo) => {
  Sentry.withScope(scope => {
    scope.setExtras(errorInfo);
    Sentry.captureException(error);
  });
};

test('componentDidCatch', () => {
  componentDidCatch('the error', 'the error info');

  const callback = Sentry.withScope.mock.calls[0][0];  // <= get the callback passed to Sentry.withScope
  const scope = { setExtras: jest.fn() };
  callback(scope);  // <= call the callback

  expect(scope.setExtras).toHaveBeenCalledWith('the error info');  // Success!
  expect(Sentry.captureException).toHaveBeenCalledWith('the error');  // Success!
});

请注意,这一行:

代码语言:javascript
复制
const callback = Sentry.withScope.mock.calls[0][0];

...is获得对Sentry.withScope的第一个调用的第一个参数,即回调函数。

票数 8
EN

Stack Overflow用户

发布于 2020-05-09 14:47:04

添加到accepted answer中。那里的解决方案需要手动调用回调(请参阅测试代码中的callback(scope); // <= call the callback行)。

下面是如何使它自动工作的方法:

代码语言:javascript
复制
import * as Sentry from '@sentry/browser'
jest.mock('@sentry/browser')

// Update the default mock implementation for `withScope` to invoke the callback
const SentryMockScope = { setExtras: jest.fn() }
Sentry.withScope.mockImplementation((callback) => {
  callback(SentryMockScope)
})

然后测试代码变成:

代码语言:javascript
复制
test('componentDidCatch', () => {
  componentDidCatch('the error', 'the error info');

  expect(SentryMockScope.setExtras).toHaveBeenCalledWith('the error info');
  expect(Sentry.captureException).toHaveBeenCalledWith('the error');
});
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56298972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档