Spying on Sentry in a jest test in a Node.js project
See original GitHub issueIs there an existing issue for this?
- I have checked for existing issues https://github.com/getsentry/sentry-javascript/issues
- I have reviewed the documentation https://docs.sentry.io/
- I am using the latest SDK release https://github.com/getsentry/sentry-javascript/releases
How do you use Sentry?
Sentry Saas (sentry.io)
Which package are you using?
SDK Version
7.1.1
Framework Version
7.1.1
Link to Sentry event
No response
Steps to Reproduce
I’m trying to spy on Sentry with jest in a Node.js project and it is not working as expected. I think from other examples I’ve looked at, spyOn
is not sufficient?
The /debug-sentry
route just throws an exception, and interactively it correctly sends an exception to Sentry. When I try to mock it like this for a test, though, the expect...toHaveBeenCalled
fails. Am I not mocking this right? Suggestions?
import * as Sentry from '@sentry/node';
...
describe('failure modes', () => {
it('send an exception to Sentry if exception thrown', async () => {
const mock = jest.spyOn(Sentry, 'captureException');
const res = await request(server).get('/debug-sentry').expect('Content-Type', /text/).expect(500);
expect(mock).toHaveBeenCalled(); // This does not succeed, not sure why...
...
The code under test (I just added the /debug-sentry
route to my server temporarily for testing):
import express from 'express';
import { Express } from 'express-serve-static-core';
import { requestLogger } from '@/utils/request_logger';
import {
initialize_exception_reporting,
initialize_error_reporting,
send_exception_message
} from '@/utils/exception_reporting';
export async function createServer(): Promise<Express> {
const server = express();
initialize_exception_reporting(server);
server.use(requestLogger);
// error customization, if request is invalid
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unused-vars
server.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
res.status(err.status).json({
error: {
type: 'request_validation',
message: err.message,
errors: err.errors,
},
});
});
server.get("/debug-sentry", (req, res) => {
throw new Error("My first Sentry error!");
});
initialize_error_reporting(server);
return server;
}
and the code setting up Sentry:
import Express from 'express';
import * as Sentry from "@sentry/node";
import * as Tracing from "@sentry/tracing";
export function initialize_exception_reporting(server: Express.Express) {
Sentry.init({
integrations: [],
});
server.use(Sentry.Handlers.requestHandler());
}
export function initialize_error_reporting(server: Express.Express) {
server.use(Sentry.Handlers.errorHandler());
}
export function send_exception_message(message: string) {
Sentry.captureMessage(message);
}
Expected Result
expect(mock).toHaveBeenCalled();
is satisfied.
Actual Result
It’s not satisfied.
Issue Analytics
- State:
- Created a year ago
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Mocking (actually, spying on) Sentry in a jest test in a Node.js ...
I'm trying to mock (well really, spyOn) Sentry with jest in a Node.js project and it is not working. The /debug-sentry route just...
Read more >Mocking Sentry in Jest and Gatsby - Bored Hacking
This is a very short and simple tutorial describing how to mock Sentry in the Jest testing framework and more specifically in a...
Read more >Spies and mocking with Jest - Node.js Developer - Željko Šević
Spy can be created by using jest.fn() . Mocking is injecting test values into the code during the tests. ... sentry.client.config.js.
Read more >Instrumenting Our Frontend Test Suite (...and fixing what we ...
In this blog post, we'll examine one such case where we use the Sentry JavaScript SDK to instrument Jest (which runs our frontend...
Read more >Testing Node.js Integrations with Jest - Taylor Callsen
Jest provides the jest.spyOn() functionality which enables mocking specific methods of a service/module, rather than the entire thing. This can ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Hi, spying on the Sentry SDK API like that probably won’t work in most cases. When an error is thrown, we usually don’t directly call the
captureException
method that is exposed by the SDK - instead we have an internal flow of execution which is not exposed.One thing you can try: Instead of spying on the API, you could use a library like
nock
to listen for outgoing requests to Sentry.This issue has gone three weeks without activity. In another week, I will close it.
But! If you comment or otherwise update it, I will reset the clock, and if you label it
Status: Backlog
orStatus: In Progress
, I will leave it alone … forever!“A weed is but an unloved flower.” ― Ella Wheeler Wilcox 🥀