Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lforst committed Jan 13, 2023
1 parent dcfa0be commit 1eb3183
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 7 deletions.
1 change: 1 addition & 0 deletions packages/nextjs/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ module.exports = {
// This prevents the build tests from running when unit tests run. (If they do, they fail, because the build being
// tested hasn't necessarily run yet.)
testPathIgnorePatterns: ['<rootDir>/test/buildProcess/'],
setupFiles: ['<rootDir>/test/setupUnitTests.ts'],
};
3 changes: 2 additions & 1 deletion packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
"devDependencies": {
"@types/webpack": "^4.41.31",
"eslint-plugin-react": "^7.31.11",
"next": "10.1.3"
"next": "10.1.3",
"whatwg-fetch": "3.6.2"
},
"peerDependencies": {
"next": "^10.0.8 || ^11.0 || ^12.0 || ^13.0",
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/src/edge/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// We cannot make any assumptions about what users define as their handler except maybe that it is a function
export interface EdgeRouteHandler {
(req: unknown): unknown | Promise<unknown>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(req: any): any | Promise<any>;
}
2 changes: 1 addition & 1 deletion packages/nextjs/src/edge/utils/edgeWrapperUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function withEdgeWrapping<H extends EdgeRouteHandler>(
try {
const handlerResult: ReturnType<H> = await handler.apply(this, args);

if (handlerResult instanceof Response) {
if ((handlerResult as unknown) instanceof Response) {
span?.setHttpStatus(handlerResult.status);
} else {
span?.setStatus('ok');
Expand Down
8 changes: 5 additions & 3 deletions packages/nextjs/src/index.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ export declare function flush(timeout?: number | undefined): PromiseLike<boolean
export declare function lastEventId(): string | undefined;
export declare function getSentryRelease(fallback?: string): string | undefined;

export declare function withSentryAPI<H extends (...args: any[]) => any>(
handler: H,
export declare function withSentryAPI<APIHandler extends (...args: any[]) => any>(
handler: APIHandler,
parameterizedRoute: string,
): (...args: Parameters<H>) => ReturnType<H> extends Promise<unknown> ? ReturnType<H> : Promise<ReturnType<H>>;
): (
...args: Parameters<APIHandler>
) => ReturnType<APIHandler> extends Promise<unknown> ? ReturnType<APIHandler> : Promise<ReturnType<APIHandler>>;
76 changes: 76 additions & 0 deletions packages/nextjs/test/edge/edgeWrapperUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import * as coreSdk from '@sentry/core';
import * as sentryTracing from '@sentry/tracing';

import { withEdgeWrapping } from '../../src/edge/utils/edgeWrapperUtils';

jest.spyOn(sentryTracing, 'hasTracingEnabled').mockImplementation(() => true);

describe('withEdgeWrapping', () => {
it('should return a function that calls the passed function', async () => {
const origFunctionReturnValue = new Response();
const origFunction = jest.fn(_req => origFunctionReturnValue);

const wrappedFunction = withEdgeWrapping(origFunction, {
spanLabel: 'some label',
mechanismFunctionName: 'some name',
spanOp: 'some op',
});

const returnValue = await wrappedFunction(new Request('https://sentry.io/'));

expect(returnValue).toBe(origFunctionReturnValue);
expect(origFunction).toHaveBeenCalledTimes(1);
});

it('should return a function that calls captureException on error', async () => {
const captureExceptionSpy = jest.spyOn(coreSdk, 'captureException');
const error = new Error();
const origFunction = jest.fn(_req => {
throw error;
});

const wrappedFunction = withEdgeWrapping(origFunction, {
spanLabel: 'some label',
mechanismFunctionName: 'some name',
spanOp: 'some op',
});

await expect(wrappedFunction(new Request('https://sentry.io/'))).rejects.toBe(error);
expect(captureExceptionSpy).toHaveBeenCalledTimes(1);
});

it('should return a function that starts a transaction when a request object is passed', async () => {
const startTransactionSpy = jest.spyOn(coreSdk, 'startTransaction');

const origFunctionReturnValue = new Response();
const origFunction = jest.fn(_req => origFunctionReturnValue);

const wrappedFunction = withEdgeWrapping(origFunction, {
spanLabel: 'some label',
mechanismFunctionName: 'some name',
spanOp: 'some op',
});

const request = new Request('https://sentry.io/');
await wrappedFunction(request);
expect(startTransactionSpy).toHaveBeenCalledTimes(1);
expect(startTransactionSpy).toHaveBeenCalledWith(
expect.objectContaining({ metadata: { source: 'route' }, name: 'some label', op: 'some op' }),
{ request },
);
});

it("should return a function that doesn't crash when req isn't passed", async () => {
const origFunctionReturnValue = new Response();
const origFunction = jest.fn(() => origFunctionReturnValue);

const wrappedFunction = withEdgeWrapping(origFunction, {
spanLabel: 'some label',
mechanismFunctionName: 'some name',
spanOp: 'some op',
});

await expect(wrappedFunction()).resolves.toBe(origFunctionReturnValue);
expect(origFunction).toHaveBeenCalledTimes(1);
});
});
1 change: 1 addition & 0 deletions packages/nextjs/test/setupUnitTests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import 'whatwg-fetch'; // polyfill fetch/Request/Response globals which edge routes need
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -25053,7 +25053,7 @@ whatwg-encoding@^2.0.0:
dependencies:
iconv-lite "0.6.3"

whatwg-fetch@>=0.10.0:
whatwg-fetch@3.6.2, whatwg-fetch@>=0.10.0:
version "3.6.2"
resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.6.2.tgz#dced24f37f2624ed0281725d51d0e2e3fe677f8c"
integrity sha512-bJlen0FcuU/0EMLrdbJ7zOnW6ITZLrZMIarMUVmdKtsGvZna8vxKYaexICWPfZ8qwf9fzNq+UEIZrnSaApt6RA==
Expand Down

0 comments on commit 1eb3183

Please sign in to comment.