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

我尝试过使用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)发布于 2019-05-25 03:52:26
未测试的行是传递给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];...is获得对Sentry.withScope的第一个调用的第一个参数,即回调函数。
发布于 2020-05-09 14:47:04
添加到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');
});https://stackoverflow.com/questions/56298972
复制相似问题