用笑话测试哨兵

时间:2019-05-24 20:10:11

标签: reactjs jestjs create-react-app sentry

我正在测试我对React的错误边界,并在Codecov中注意到我的Sentry函数的特定部分尚未经过测试。

enter image description here

我尝试使用jest.mock(“ @ sentry / browser”)和嘲笑Sentry,但是似乎无法测试这些行。 Sentry导入可以正确模拟,但scope不能。

这是我尝试嘲笑的一个例子。

import * as Sentry from "@sentry/browser"
const mock_scope = jest.fn(() => {
  return { setExtras: null }
})
Sentry.withScope = jest.fn().mockImplementation(mock_scope)

2 个答案:

答案 0 :(得分:2)

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

这是使其自动运行的方法:

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

然后测试代码变为:

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

  expect(SentryMockScope.setExtras).toHaveBeenCalledWith('the error info');
  expect(Sentry.captureException).toHaveBeenCalledWith('the error');
});

答案 1 :(得分:1)

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

scope => {
  scope.setExtras(errorInfo);
  Sentry.captureException(error);
}

Sentry.withScope被嘲笑以来,您可以使用mockFn.mock.calls检索传递给它的回调函数。

检索到回调函数后,可以直接调用它进行测试。

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

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

请注意这一行:

const callback = Sentry.withScope.mock.calls[0][0];

...正在获取对Sentry.withScope的首次调用的第一个参数,这是回调函数。