Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions packages/nextjs/jest.config.js

This file was deleted.

4 changes: 2 additions & 2 deletions packages/nextjs/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -117,8 +117,8 @@
"lint": "eslint . --format stylish",
"test": "yarn test:unit",
"test:all": "run-s test:unit",
"test:unit": "jest",
"test:watch": "jest --watch",
"test:unit": "vitest run",
"test:watch": "vitest --watch",
"vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh",
"vercel:project": "source vercel/make-project-use-current-branch.sh",
"yalc:publish": "yalc publish --push --sig"
Expand Down
9 changes: 5 additions & 4 deletions packages/nextjs/test/clientSdk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import type { Integration } from '@sentry/core';
import * as SentryReact from '@sentry/react';
import { WINDOW, getClient, getCurrentScope } from '@sentry/react';
import { JSDOM } from 'jsdom';
import { describe, vi, afterAll, afterEach, it, expect } from 'vitest';

import { breadcrumbsIntegration, browserTracingIntegration, init } from '../src/client';

const reactInit = jest.spyOn(SentryReact, 'init');
const loggerLogSpy = jest.spyOn(logger, 'log');
const reactInit = vi.spyOn(SentryReact, 'init');
const loggerLogSpy = vi.spyOn(logger, 'log');

// We're setting up JSDom here because the Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
Expand DownExpand Up@@ -38,7 +39,7 @@ const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337';

describe('Client init()', () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();

getGlobalScope().clear();
getIsolationScope().clear();
Expand DownExpand Up@@ -83,7 +84,7 @@ describe('Client init()', () => {
dsn: 'https://dogsarebadatkeepingsecrets@squirrelchasers.ingest.sentry.io/12312012',
tracesSampleRate: 1.0,
});
const transportSend = jest.spyOn(getClient()!.getTransport()!, 'send');
const transportSend = vi.spyOn(getClient()!.getTransport()!, 'send');

// Ensure we have no current span, so our next span is a transaction
SentryReact.withActiveSpan(null, () => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`valueInjectionLoader should correctly insert values for basic config 1`] = `
exports[`valueInjectionLoader > should correctly insert values for basic config 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";import * as Sentry from '@sentry/nextjs';
;globalThis["foo"] = "bar";import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with a misplaced directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with a misplaced directive 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";console.log('This will render the directive useless');
\\"use client\\";
;globalThis["foo"] = "bar";console.log('This will render the directive useless');
"use client";



Expand All@@ -19,44 +19,44 @@ exports[`valueInjectionLoader should correctly insert values with a misplaced di
"
`;

exports[`valueInjectionLoader should correctly insert values with directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive 1`] = `
"
\\"use client\\";globalThis[\\"foo\\"] = \\"bar\\";
"use client";globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and block comments 1`] = `
"
/* test */
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and inline comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and inline comments 1`] = `
"
// test
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments 1`] = `
"
/*
test
*/
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
"
/*
test
Expand All@@ -65,7 +65,7 @@ exports[`valueInjectionLoader should correctly insert values with directive and



\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";



Expand All@@ -74,9 +74,9 @@ exports[`valueInjectionLoader should correctly insert values with directive and
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and semicolon 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and semicolon 1`] = `
"
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
Expand Down
42 changes: 8 additions & 34 deletions packages/nextjs/test/config/loaders.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
import './mocks';

import * as fs from 'fs';
import { describe, vi, it, expect } from 'vitest';

import type { ModuleRuleUseProperty, WebpackModuleRule } from '../../src/config/types';
import {
Expand All@@ -13,36 +14,8 @@ import {
} from './fixtures';
import { materializeFinalWebpackConfig } from './testUtils';

const existsSyncSpy = jest.spyOn(fs, 'existsSync');
const lstatSyncSpy = jest.spyOn(fs, 'lstatSync');

type MatcherResult = { pass: boolean; message: () => string };

expect.extend({
stringEndingWith(received: string, expectedEnding: string): MatcherResult {
const failsTest = !received.endsWith(expectedEnding);
const generateErrorMessage = () =>
failsTest
? // Regular error message for match failing
`expected string ending with '${expectedEnding}', but got '${received}'`
: // Error message for the match passing if someone has called it with `expect.not`
`expected string not ending with '${expectedEnding}', but got '${received}'`;

return {
pass: !failsTest,
message: generateErrorMessage,
};
},
});

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Expect {
stringEndingWith: (expectedEnding: string) => MatcherResult;
}
}
}
const existsSyncSpy = vi.spyOn(fs, 'existsSync');
const lstatSyncSpy = vi.spyOn(fs, 'lstatSync');

function applyRuleToResource(rule: WebpackModuleRule, resourcePath: string): ModuleRuleUseProperty[] {
const applications = [];
Expand DownExpand Up@@ -80,7 +53,7 @@ describe('webpack loaders', () => {
test: expect.any(RegExp),
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand DownExpand Up@@ -272,7 +245,7 @@ describe('webpack loaders', () => {
test: /sentry\.client\.config\.(jsx?|tsx?)/,
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand All@@ -285,9 +258,10 @@ describe('webpack loaders', () => {
});

describe('`distDir` value in default server-side `RewriteFrames` integration', () => {
describe('`RewriteFrames` ends up with correct `distDir` value', () => {
it('`RewriteFrames` ends up with correct `distDir` value', () => {
// TODO: this, along with any number of other parts of the build process, should be tested with an integration
// test which actually runs webpack and inspects the resulting bundles (and that integration test should test
// custom `distDir` values with and without a `.`, to make sure the regex escaping is working)
// custom `distDir` values with and without a `.`, to make sure the regex
// escaping is working)
});
});
21 changes: 15 additions & 6 deletions packages/nextjs/test/config/mocks.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { vi, afterAll, afterEach } from 'vitest';

vi.mock('fs');
vi.mock('os');

import { CLIENT_SDK_CONFIG_FILE, EDGE_SDK_CONFIG_FILE, SERVER_SDK_CONFIG_FILE } from './fixtures';

// We use `fs.existsSync()` in `getUserConfigFile()`. When we're not testing `getUserConfigFile()` specifically, all we
// need is for it to give us any valid answer, so make it always find what it's looking for. Since this is a core node
// built-in, though, which jest itself uses, otherwise let it do the normal thing. Storing the real version of the
// function also lets us restore the original when we do want to test `getUserConfigFile()`.
export const realExistsSync = jest.requireActual('fs').existsSync;
// function also lets us restore the original when we do want to test
// `getUserConfigFile()`.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const fsReal = (await vi.importActual('fs')) as typeof import('fs');
export const realExistsSync = fsReal.existsSync;
export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsSync> => {
if (
(path as string).endsWith(SERVER_SDK_CONFIG_FILE) ||
Expand All@@ -23,20 +30,22 @@ export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsS

return realExistsSync(path);
};
export const exitsSync = jest.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);
export const exitsSync = vi.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);

/** Mocking of temporary directory creation (so that we have a place to stick files (like `sentry.client.config.js`) in
* order to test that we can find them) */

// Make it so that all temporary folders, either created directly by tests or by the code they're testing, will go into
// one spot that we know about, which we can then clean up when we're done
const realTmpdir = jest.requireActual('os').tmpdir;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const osReal = (await vi.importActual('os')) as typeof import('os');
const realTmpdir = osReal.tmpdir;

// Including the random number ensures that even if multiple test files using these mocks are running at once, they have
// separate temporary folders
const TEMP_DIR_PATH = path.join(realTmpdir(), `sentry-nextjs-test-${Math.random()}`);

jest.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
vi.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
// In theory, we should always land in the `else` here, but this saves the cases where the prior run got interrupted and
// the `afterAll` below didn't happen.
if (fs.existsSync(TEMP_DIR_PATH)) {
Expand All@@ -52,7 +61,7 @@ afterAll(() => {
// In order to know what to expect in the webpack config `entry` property, we need to know the path of the temporary
// directory created when doing the file injection, so wrap the real `mkdtempSync` and store the resulting path where we
// can access it
export const mkdtempSyncSpy = jest.spyOn(fs, 'mkdtempSync');
export const mkdtempSyncSpy = vi.spyOn(fs, 'mkdtempSync');

afterEach(() => {
mkdtempSyncSpy.mockClear();
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/test/config/valueInjectionLoader.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { LoaderThis } from '../../src/config/loaders/types';
import type { ValueInjectionLoaderOptions } from '../../src/config/loaders/valueInjectionLoader';
import valueInjectionLoader from '../../src/config/loaders/valueInjectionLoader';
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, vi } from 'vitest';

// mock helper functions not tested directly in this file
import '../mocks';

Expand All@@ -12,9 +14,16 @@ import {
userNextConfig,
} from '../fixtures';
import { materializeFinalNextConfig, materializeFinalWebpackConfig } from '../testUtils';
import * as core from '@sentry/core';

describe('constructWebpackConfigFunction()', () => {
it('includes expected properties', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig,
incomingWebpackConfig: serverWebpackConfig,
Expand DownExpand Up@@ -46,7 +55,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => {
const getWebpackPluginOptionsSpy = jest.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
const getWebpackPluginOptionsSpy = vi.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

await materializeFinalWebpackConfig({
exportedNextConfig,
Expand DownExpand Up@@ -112,6 +126,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('uses `hidden-source-map` as `devtool` value for client-side builds', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalClientWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig: exportedNextConfig,
incomingWebpackConfig: clientWebpackConfig,
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { BuildContext, NextConfigObject } from '../../../src/config/types';
import { getWebpackPluginOptions } from '../../../src/config/webpackPluginOptions';

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
import * as SentryCore from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { describe, vi, beforeEach, afterEach, it, expect } from 'vitest';

import type { AugmentedNextApiResponse, NextApiHandler } from '../../src/common/types';
import { wrapApiHandlerWithSentry } from '../../src/server';

const startSpanManualSpy = jest.spyOn(SentryCore, 'startSpanManual');
const startSpanManualSpy = vi.spyOn(SentryCore, 'startSpanManual');

describe('withSentry', () => {
let req: NextApiRequest, res: NextApiResponse;
Expand All@@ -32,7 +33,7 @@ describe('withSentry', () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('tracing', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/test/config/withSentryConfig.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, vi, it, expect } from 'vitest';

import { defaultRuntimePhase, defaultsObject, exportedNextConfig, userNextConfig } from './fixtures';
import { materializeFinalNextConfig } from './testUtils';

Expand DownExpand Up@@ -43,7 +45,7 @@ describe('withSentryConfig', () => {
});

it('correctly passes `phase` and `defaultConfig` through to functional `userNextConfig`', () => {
const exportedNextConfigFunction = jest.fn().mockReturnValue(userNextConfig);
const exportedNextConfigFunction = vi.fn().mockReturnValue(userNextConfig);

materializeFinalNextConfig(exportedNextConfigFunction);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
test(nextjs): Migrate to Vitest by timfish · Pull Request #15546 · getsentry/sentry-javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions packages/nextjs/jest.config.js

This file was deleted.

4 changes: 2 additions & 2 deletions packages/nextjs/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -117,8 +117,8 @@
"lint": "eslint . --format stylish",
"test": "yarn test:unit",
"test:all": "run-s test:unit",
"test:unit": "jest",
"test:watch": "jest --watch",
"test:unit": "vitest run",
"test:watch": "vitest --watch",
"vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh",
"vercel:project": "source vercel/make-project-use-current-branch.sh",
"yalc:publish": "yalc publish --push --sig"
Expand Down
9 changes: 5 additions & 4 deletions packages/nextjs/test/clientSdk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import type { Integration } from '@sentry/core';
import * as SentryReact from '@sentry/react';
import { WINDOW, getClient, getCurrentScope } from '@sentry/react';
import { JSDOM } from 'jsdom';
import { describe, vi, afterAll, afterEach, it, expect } from 'vitest';

import { breadcrumbsIntegration, browserTracingIntegration, init } from '../src/client';

const reactInit = jest.spyOn(SentryReact, 'init');
const loggerLogSpy = jest.spyOn(logger, 'log');
const reactInit = vi.spyOn(SentryReact, 'init');
const loggerLogSpy = vi.spyOn(logger, 'log');

// We're setting up JSDom here because the Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
Expand DownExpand Up@@ -38,7 +39,7 @@ const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337';

describe('Client init()', () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();

getGlobalScope().clear();
getIsolationScope().clear();
Expand DownExpand Up@@ -83,7 +84,7 @@ describe('Client init()', () => {
dsn: 'https://dogsarebadatkeepingsecrets@squirrelchasers.ingest.sentry.io/12312012',
tracesSampleRate: 1.0,
});
const transportSend = jest.spyOn(getClient()!.getTransport()!, 'send');
const transportSend = vi.spyOn(getClient()!.getTransport()!, 'send');

// Ensure we have no current span, so our next span is a transaction
SentryReact.withActiveSpan(null, () => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`valueInjectionLoader should correctly insert values for basic config 1`] = `
exports[`valueInjectionLoader > should correctly insert values for basic config 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";import * as Sentry from '@sentry/nextjs';
;globalThis["foo"] = "bar";import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with a misplaced directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with a misplaced directive 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";console.log('This will render the directive useless');
\\"use client\\";
;globalThis["foo"] = "bar";console.log('This will render the directive useless');
"use client";



Expand All@@ -19,44 +19,44 @@ exports[`valueInjectionLoader should correctly insert values with a misplaced di
"
`;

exports[`valueInjectionLoader should correctly insert values with directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive 1`] = `
"
\\"use client\\";globalThis[\\"foo\\"] = \\"bar\\";
"use client";globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and block comments 1`] = `
"
/* test */
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and inline comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and inline comments 1`] = `
"
// test
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments 1`] = `
"
/*
test
*/
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
"
/*
test
Expand All@@ -65,7 +65,7 @@ exports[`valueInjectionLoader should correctly insert values with directive and



\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";



Expand All@@ -74,9 +74,9 @@ exports[`valueInjectionLoader should correctly insert values with directive and
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and semicolon 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and semicolon 1`] = `
"
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
Expand Down
42 changes: 8 additions & 34 deletions packages/nextjs/test/config/loaders.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
import './mocks';

import * as fs from 'fs';
import { describe, vi, it, expect } from 'vitest';

import type { ModuleRuleUseProperty, WebpackModuleRule } from '../../src/config/types';
import {
Expand All@@ -13,36 +14,8 @@ import {
} from './fixtures';
import { materializeFinalWebpackConfig } from './testUtils';

const existsSyncSpy = jest.spyOn(fs, 'existsSync');
const lstatSyncSpy = jest.spyOn(fs, 'lstatSync');

type MatcherResult = { pass: boolean; message: () => string };

expect.extend({
stringEndingWith(received: string, expectedEnding: string): MatcherResult {
const failsTest = !received.endsWith(expectedEnding);
const generateErrorMessage = () =>
failsTest
? // Regular error message for match failing
`expected string ending with '${expectedEnding}', but got '${received}'`
: // Error message for the match passing if someone has called it with `expect.not`
`expected string not ending with '${expectedEnding}', but got '${received}'`;

return {
pass: !failsTest,
message: generateErrorMessage,
};
},
});

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Expect {
stringEndingWith: (expectedEnding: string) => MatcherResult;
}
}
}
const existsSyncSpy = vi.spyOn(fs, 'existsSync');
const lstatSyncSpy = vi.spyOn(fs, 'lstatSync');

function applyRuleToResource(rule: WebpackModuleRule, resourcePath: string): ModuleRuleUseProperty[] {
const applications = [];
Expand DownExpand Up@@ -80,7 +53,7 @@ describe('webpack loaders', () => {
test: expect.any(RegExp),
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand DownExpand Up@@ -272,7 +245,7 @@ describe('webpack loaders', () => {
test: /sentry\.client\.config\.(jsx?|tsx?)/,
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand All@@ -285,9 +258,10 @@ describe('webpack loaders', () => {
});

describe('`distDir` value in default server-side `RewriteFrames` integration', () => {
describe('`RewriteFrames` ends up with correct `distDir` value', () => {
it('`RewriteFrames` ends up with correct `distDir` value', () => {
// TODO: this, along with any number of other parts of the build process, should be tested with an integration
// test which actually runs webpack and inspects the resulting bundles (and that integration test should test
// custom `distDir` values with and without a `.`, to make sure the regex escaping is working)
// custom `distDir` values with and without a `.`, to make sure the regex
// escaping is working)
});
});
21 changes: 15 additions & 6 deletions packages/nextjs/test/config/mocks.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { vi, afterAll, afterEach } from 'vitest';

vi.mock('fs');
vi.mock('os');

import { CLIENT_SDK_CONFIG_FILE, EDGE_SDK_CONFIG_FILE, SERVER_SDK_CONFIG_FILE } from './fixtures';

// We use `fs.existsSync()` in `getUserConfigFile()`. When we're not testing `getUserConfigFile()` specifically, all we
// need is for it to give us any valid answer, so make it always find what it's looking for. Since this is a core node
// built-in, though, which jest itself uses, otherwise let it do the normal thing. Storing the real version of the
// function also lets us restore the original when we do want to test `getUserConfigFile()`.
export const realExistsSync = jest.requireActual('fs').existsSync;
// function also lets us restore the original when we do want to test
// `getUserConfigFile()`.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const fsReal = (await vi.importActual('fs')) as typeof import('fs');
export const realExistsSync = fsReal.existsSync;
export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsSync> => {
if (
(path as string).endsWith(SERVER_SDK_CONFIG_FILE) ||
Expand All@@ -23,20 +30,22 @@ export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsS

return realExistsSync(path);
};
export const exitsSync = jest.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);
export const exitsSync = vi.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);

/** Mocking of temporary directory creation (so that we have a place to stick files (like `sentry.client.config.js`) in
* order to test that we can find them) */

// Make it so that all temporary folders, either created directly by tests or by the code they're testing, will go into
// one spot that we know about, which we can then clean up when we're done
const realTmpdir = jest.requireActual('os').tmpdir;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const osReal = (await vi.importActual('os')) as typeof import('os');
const realTmpdir = osReal.tmpdir;

// Including the random number ensures that even if multiple test files using these mocks are running at once, they have
// separate temporary folders
const TEMP_DIR_PATH = path.join(realTmpdir(), `sentry-nextjs-test-${Math.random()}`);

jest.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
vi.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
// In theory, we should always land in the `else` here, but this saves the cases where the prior run got interrupted and
// the `afterAll` below didn't happen.
if (fs.existsSync(TEMP_DIR_PATH)) {
Expand All@@ -52,7 +61,7 @@ afterAll(() => {
// In order to know what to expect in the webpack config `entry` property, we need to know the path of the temporary
// directory created when doing the file injection, so wrap the real `mkdtempSync` and store the resulting path where we
// can access it
export const mkdtempSyncSpy = jest.spyOn(fs, 'mkdtempSync');
export const mkdtempSyncSpy = vi.spyOn(fs, 'mkdtempSync');

afterEach(() => {
mkdtempSyncSpy.mockClear();
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/test/config/valueInjectionLoader.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { LoaderThis } from '../../src/config/loaders/types';
import type { ValueInjectionLoaderOptions } from '../../src/config/loaders/valueInjectionLoader';
import valueInjectionLoader from '../../src/config/loaders/valueInjectionLoader';
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, vi } from 'vitest';

// mock helper functions not tested directly in this file
import '../mocks';

Expand All@@ -12,9 +14,16 @@ import {
userNextConfig,
} from '../fixtures';
import { materializeFinalNextConfig, materializeFinalWebpackConfig } from '../testUtils';
import * as core from '@sentry/core';

describe('constructWebpackConfigFunction()', () => {
it('includes expected properties', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig,
incomingWebpackConfig: serverWebpackConfig,
Expand DownExpand Up@@ -46,7 +55,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => {
const getWebpackPluginOptionsSpy = jest.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
const getWebpackPluginOptionsSpy = vi.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

await materializeFinalWebpackConfig({
exportedNextConfig,
Expand DownExpand Up@@ -112,6 +126,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('uses `hidden-source-map` as `devtool` value for client-side builds', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalClientWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig: exportedNextConfig,
incomingWebpackConfig: clientWebpackConfig,
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { BuildContext, NextConfigObject } from '../../../src/config/types';
import { getWebpackPluginOptions } from '../../../src/config/webpackPluginOptions';

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
import * as SentryCore from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { describe, vi, beforeEach, afterEach, it, expect } from 'vitest';

import type { AugmentedNextApiResponse, NextApiHandler } from '../../src/common/types';
import { wrapApiHandlerWithSentry } from '../../src/server';

const startSpanManualSpy = jest.spyOn(SentryCore, 'startSpanManual');
const startSpanManualSpy = vi.spyOn(SentryCore, 'startSpanManual');

describe('withSentry', () => {
let req: NextApiRequest, res: NextApiResponse;
Expand All@@ -32,7 +33,7 @@ describe('withSentry', () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('tracing', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/test/config/withSentryConfig.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, vi, it, expect } from 'vitest';

import { defaultRuntimePhase, defaultsObject, exportedNextConfig, userNextConfig } from './fixtures';
import { materializeFinalNextConfig } from './testUtils';

Expand DownExpand Up@@ -43,7 +45,7 @@ describe('withSentryConfig', () => {
});

it('correctly passes `phase` and `defaultConfig` through to functional `userNextConfig`', () => {
const exportedNextConfigFunction = jest.fn().mockReturnValue(userNextConfig);
const exportedNextConfigFunction = vi.fn().mockReturnValue(userNextConfig);

materializeFinalNextConfig(exportedNextConfigFunction);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' test(nextjs): Migrate to Vitest by timfish · Pull Request #15546 · getsentry/sentry-javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions packages/nextjs/jest.config.js

This file was deleted.

4 changes: 2 additions & 2 deletions packages/nextjs/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -117,8 +117,8 @@
"lint": "eslint . --format stylish",
"test": "yarn test:unit",
"test:all": "run-s test:unit",
"test:unit": "jest",
"test:watch": "jest --watch",
"test:unit": "vitest run",
"test:watch": "vitest --watch",
"vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh",
"vercel:project": "source vercel/make-project-use-current-branch.sh",
"yalc:publish": "yalc publish --push --sig"
Expand Down
9 changes: 5 additions & 4 deletions packages/nextjs/test/clientSdk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import type { Integration } from '@sentry/core';
import * as SentryReact from '@sentry/react';
import { WINDOW, getClient, getCurrentScope } from '@sentry/react';
import { JSDOM } from 'jsdom';
import { describe, vi, afterAll, afterEach, it, expect } from 'vitest';

import { breadcrumbsIntegration, browserTracingIntegration, init } from '../src/client';

const reactInit = jest.spyOn(SentryReact, 'init');
const loggerLogSpy = jest.spyOn(logger, 'log');
const reactInit = vi.spyOn(SentryReact, 'init');
const loggerLogSpy = vi.spyOn(logger, 'log');

// We're setting up JSDom here because the Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
Expand DownExpand Up@@ -38,7 +39,7 @@ const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337';

describe('Client init()', () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();

getGlobalScope().clear();
getIsolationScope().clear();
Expand DownExpand Up@@ -83,7 +84,7 @@ describe('Client init()', () => {
dsn: 'https://dogsarebadatkeepingsecrets@squirrelchasers.ingest.sentry.io/12312012',
tracesSampleRate: 1.0,
});
const transportSend = jest.spyOn(getClient()!.getTransport()!, 'send');
const transportSend = vi.spyOn(getClient()!.getTransport()!, 'send');

// Ensure we have no current span, so our next span is a transaction
SentryReact.withActiveSpan(null, () => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`valueInjectionLoader should correctly insert values for basic config 1`] = `
exports[`valueInjectionLoader > should correctly insert values for basic config 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";import * as Sentry from '@sentry/nextjs';
;globalThis["foo"] = "bar";import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with a misplaced directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with a misplaced directive 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";console.log('This will render the directive useless');
\\"use client\\";
;globalThis["foo"] = "bar";console.log('This will render the directive useless');
"use client";



Expand All@@ -19,44 +19,44 @@ exports[`valueInjectionLoader should correctly insert values with a misplaced di
"
`;

exports[`valueInjectionLoader should correctly insert values with directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive 1`] = `
"
\\"use client\\";globalThis[\\"foo\\"] = \\"bar\\";
"use client";globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and block comments 1`] = `
"
/* test */
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and inline comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and inline comments 1`] = `
"
// test
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments 1`] = `
"
/*
test
*/
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
"
/*
test
Expand All@@ -65,7 +65,7 @@ exports[`valueInjectionLoader should correctly insert values with directive and



\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";



Expand All@@ -74,9 +74,9 @@ exports[`valueInjectionLoader should correctly insert values with directive and
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and semicolon 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and semicolon 1`] = `
"
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
Expand Down
42 changes: 8 additions & 34 deletions packages/nextjs/test/config/loaders.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
import './mocks';

import * as fs from 'fs';
import { describe, vi, it, expect } from 'vitest';

import type { ModuleRuleUseProperty, WebpackModuleRule } from '../../src/config/types';
import {
Expand All@@ -13,36 +14,8 @@ import {
} from './fixtures';
import { materializeFinalWebpackConfig } from './testUtils';

const existsSyncSpy = jest.spyOn(fs, 'existsSync');
const lstatSyncSpy = jest.spyOn(fs, 'lstatSync');

type MatcherResult = { pass: boolean; message: () => string };

expect.extend({
stringEndingWith(received: string, expectedEnding: string): MatcherResult {
const failsTest = !received.endsWith(expectedEnding);
const generateErrorMessage = () =>
failsTest
? // Regular error message for match failing
`expected string ending with '${expectedEnding}', but got '${received}'`
: // Error message for the match passing if someone has called it with `expect.not`
`expected string not ending with '${expectedEnding}', but got '${received}'`;

return {
pass: !failsTest,
message: generateErrorMessage,
};
},
});

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Expect {
stringEndingWith: (expectedEnding: string) => MatcherResult;
}
}
}
const existsSyncSpy = vi.spyOn(fs, 'existsSync');
const lstatSyncSpy = vi.spyOn(fs, 'lstatSync');

function applyRuleToResource(rule: WebpackModuleRule, resourcePath: string): ModuleRuleUseProperty[] {
const applications = [];
Expand DownExpand Up@@ -80,7 +53,7 @@ describe('webpack loaders', () => {
test: expect.any(RegExp),
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand DownExpand Up@@ -272,7 +245,7 @@ describe('webpack loaders', () => {
test: /sentry\.client\.config\.(jsx?|tsx?)/,
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand All@@ -285,9 +258,10 @@ describe('webpack loaders', () => {
});

describe('`distDir` value in default server-side `RewriteFrames` integration', () => {
describe('`RewriteFrames` ends up with correct `distDir` value', () => {
it('`RewriteFrames` ends up with correct `distDir` value', () => {
// TODO: this, along with any number of other parts of the build process, should be tested with an integration
// test which actually runs webpack and inspects the resulting bundles (and that integration test should test
// custom `distDir` values with and without a `.`, to make sure the regex escaping is working)
// custom `distDir` values with and without a `.`, to make sure the regex
// escaping is working)
});
});
21 changes: 15 additions & 6 deletions packages/nextjs/test/config/mocks.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { vi, afterAll, afterEach } from 'vitest';

vi.mock('fs');
vi.mock('os');

import { CLIENT_SDK_CONFIG_FILE, EDGE_SDK_CONFIG_FILE, SERVER_SDK_CONFIG_FILE } from './fixtures';

// We use `fs.existsSync()` in `getUserConfigFile()`. When we're not testing `getUserConfigFile()` specifically, all we
// need is for it to give us any valid answer, so make it always find what it's looking for. Since this is a core node
// built-in, though, which jest itself uses, otherwise let it do the normal thing. Storing the real version of the
// function also lets us restore the original when we do want to test `getUserConfigFile()`.
export const realExistsSync = jest.requireActual('fs').existsSync;
// function also lets us restore the original when we do want to test
// `getUserConfigFile()`.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const fsReal = (await vi.importActual('fs')) as typeof import('fs');
export const realExistsSync = fsReal.existsSync;
export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsSync> => {
if (
(path as string).endsWith(SERVER_SDK_CONFIG_FILE) ||
Expand All@@ -23,20 +30,22 @@ export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsS

return realExistsSync(path);
};
export const exitsSync = jest.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);
export const exitsSync = vi.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);

/** Mocking of temporary directory creation (so that we have a place to stick files (like `sentry.client.config.js`) in
* order to test that we can find them) */

// Make it so that all temporary folders, either created directly by tests or by the code they're testing, will go into
// one spot that we know about, which we can then clean up when we're done
const realTmpdir = jest.requireActual('os').tmpdir;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const osReal = (await vi.importActual('os')) as typeof import('os');
const realTmpdir = osReal.tmpdir;

// Including the random number ensures that even if multiple test files using these mocks are running at once, they have
// separate temporary folders
const TEMP_DIR_PATH = path.join(realTmpdir(), `sentry-nextjs-test-${Math.random()}`);

jest.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
vi.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
// In theory, we should always land in the `else` here, but this saves the cases where the prior run got interrupted and
// the `afterAll` below didn't happen.
if (fs.existsSync(TEMP_DIR_PATH)) {
Expand All@@ -52,7 +61,7 @@ afterAll(() => {
// In order to know what to expect in the webpack config `entry` property, we need to know the path of the temporary
// directory created when doing the file injection, so wrap the real `mkdtempSync` and store the resulting path where we
// can access it
export const mkdtempSyncSpy = jest.spyOn(fs, 'mkdtempSync');
export const mkdtempSyncSpy = vi.spyOn(fs, 'mkdtempSync');

afterEach(() => {
mkdtempSyncSpy.mockClear();
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/test/config/valueInjectionLoader.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { LoaderThis } from '../../src/config/loaders/types';
import type { ValueInjectionLoaderOptions } from '../../src/config/loaders/valueInjectionLoader';
import valueInjectionLoader from '../../src/config/loaders/valueInjectionLoader';
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, vi } from 'vitest';

// mock helper functions not tested directly in this file
import '../mocks';

Expand All@@ -12,9 +14,16 @@ import {
userNextConfig,
} from '../fixtures';
import { materializeFinalNextConfig, materializeFinalWebpackConfig } from '../testUtils';
import * as core from '@sentry/core';

describe('constructWebpackConfigFunction()', () => {
it('includes expected properties', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig,
incomingWebpackConfig: serverWebpackConfig,
Expand DownExpand Up@@ -46,7 +55,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => {
const getWebpackPluginOptionsSpy = jest.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
const getWebpackPluginOptionsSpy = vi.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

await materializeFinalWebpackConfig({
exportedNextConfig,
Expand DownExpand Up@@ -112,6 +126,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('uses `hidden-source-map` as `devtool` value for client-side builds', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalClientWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig: exportedNextConfig,
incomingWebpackConfig: clientWebpackConfig,
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { BuildContext, NextConfigObject } from '../../../src/config/types';
import { getWebpackPluginOptions } from '../../../src/config/webpackPluginOptions';

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
import * as SentryCore from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { describe, vi, beforeEach, afterEach, it, expect } from 'vitest';

import type { AugmentedNextApiResponse, NextApiHandler } from '../../src/common/types';
import { wrapApiHandlerWithSentry } from '../../src/server';

const startSpanManualSpy = jest.spyOn(SentryCore, 'startSpanManual');
const startSpanManualSpy = vi.spyOn(SentryCore, 'startSpanManual');

describe('withSentry', () => {
let req: NextApiRequest, res: NextApiResponse;
Expand All@@ -32,7 +33,7 @@ describe('withSentry', () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('tracing', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/test/config/withSentryConfig.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, vi, it, expect } from 'vitest';

import { defaultRuntimePhase, defaultsObject, exportedNextConfig, userNextConfig } from './fixtures';
import { materializeFinalNextConfig } from './testUtils';

Expand DownExpand Up@@ -43,7 +45,7 @@ describe('withSentryConfig', () => {
});

it('correctly passes `phase` and `defaultConfig` through to functional `userNextConfig`', () => {
const exportedNextConfigFunction = jest.fn().mockReturnValue(userNextConfig);
const exportedNextConfigFunction = vi.fn().mockReturnValue(userNextConfig);

materializeFinalNextConfig(exportedNextConfigFunction);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' test(nextjs): Migrate to Vitest by timfish · Pull Request #15546 · getsentry/sentry-javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions packages/nextjs/jest.config.js

This file was deleted.

4 changes: 2 additions & 2 deletions packages/nextjs/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -117,8 +117,8 @@
"lint": "eslint . --format stylish",
"test": "yarn test:unit",
"test:all": "run-s test:unit",
"test:unit": "jest",
"test:watch": "jest --watch",
"test:unit": "vitest run",
"test:watch": "vitest --watch",
"vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh",
"vercel:project": "source vercel/make-project-use-current-branch.sh",
"yalc:publish": "yalc publish --push --sig"
Expand Down
9 changes: 5 additions & 4 deletions packages/nextjs/test/clientSdk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import type { Integration } from '@sentry/core';
import * as SentryReact from '@sentry/react';
import { WINDOW, getClient, getCurrentScope } from '@sentry/react';
import { JSDOM } from 'jsdom';
import { describe, vi, afterAll, afterEach, it, expect } from 'vitest';

import { breadcrumbsIntegration, browserTracingIntegration, init } from '../src/client';

const reactInit = jest.spyOn(SentryReact, 'init');
const loggerLogSpy = jest.spyOn(logger, 'log');
const reactInit = vi.spyOn(SentryReact, 'init');
const loggerLogSpy = vi.spyOn(logger, 'log');

// We're setting up JSDom here because the Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
Expand DownExpand Up@@ -38,7 +39,7 @@ const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337';

describe('Client init()', () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();

getGlobalScope().clear();
getIsolationScope().clear();
Expand DownExpand Up@@ -83,7 +84,7 @@ describe('Client init()', () => {
dsn: 'https://dogsarebadatkeepingsecrets@squirrelchasers.ingest.sentry.io/12312012',
tracesSampleRate: 1.0,
});
const transportSend = jest.spyOn(getClient()!.getTransport()!, 'send');
const transportSend = vi.spyOn(getClient()!.getTransport()!, 'send');

// Ensure we have no current span, so our next span is a transaction
SentryReact.withActiveSpan(null, () => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`valueInjectionLoader should correctly insert values for basic config 1`] = `
exports[`valueInjectionLoader > should correctly insert values for basic config 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";import * as Sentry from '@sentry/nextjs';
;globalThis["foo"] = "bar";import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with a misplaced directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with a misplaced directive 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";console.log('This will render the directive useless');
\\"use client\\";
;globalThis["foo"] = "bar";console.log('This will render the directive useless');
"use client";



Expand All@@ -19,44 +19,44 @@ exports[`valueInjectionLoader should correctly insert values with a misplaced di
"
`;

exports[`valueInjectionLoader should correctly insert values with directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive 1`] = `
"
\\"use client\\";globalThis[\\"foo\\"] = \\"bar\\";
"use client";globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and block comments 1`] = `
"
/* test */
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and inline comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and inline comments 1`] = `
"
// test
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments 1`] = `
"
/*
test
*/
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
"
/*
test
Expand All@@ -65,7 +65,7 @@ exports[`valueInjectionLoader should correctly insert values with directive and



\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";



Expand All@@ -74,9 +74,9 @@ exports[`valueInjectionLoader should correctly insert values with directive and
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and semicolon 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and semicolon 1`] = `
"
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
Expand Down
42 changes: 8 additions & 34 deletions packages/nextjs/test/config/loaders.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
import './mocks';

import * as fs from 'fs';
import { describe, vi, it, expect } from 'vitest';

import type { ModuleRuleUseProperty, WebpackModuleRule } from '../../src/config/types';
import {
Expand All@@ -13,36 +14,8 @@ import {
} from './fixtures';
import { materializeFinalWebpackConfig } from './testUtils';

const existsSyncSpy = jest.spyOn(fs, 'existsSync');
const lstatSyncSpy = jest.spyOn(fs, 'lstatSync');

type MatcherResult = { pass: boolean; message: () => string };

expect.extend({
stringEndingWith(received: string, expectedEnding: string): MatcherResult {
const failsTest = !received.endsWith(expectedEnding);
const generateErrorMessage = () =>
failsTest
? // Regular error message for match failing
`expected string ending with '${expectedEnding}', but got '${received}'`
: // Error message for the match passing if someone has called it with `expect.not`
`expected string not ending with '${expectedEnding}', but got '${received}'`;

return {
pass: !failsTest,
message: generateErrorMessage,
};
},
});

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Expect {
stringEndingWith: (expectedEnding: string) => MatcherResult;
}
}
}
const existsSyncSpy = vi.spyOn(fs, 'existsSync');
const lstatSyncSpy = vi.spyOn(fs, 'lstatSync');

function applyRuleToResource(rule: WebpackModuleRule, resourcePath: string): ModuleRuleUseProperty[] {
const applications = [];
Expand DownExpand Up@@ -80,7 +53,7 @@ describe('webpack loaders', () => {
test: expect.any(RegExp),
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand DownExpand Up@@ -272,7 +245,7 @@ describe('webpack loaders', () => {
test: /sentry\.client\.config\.(jsx?|tsx?)/,
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand All@@ -285,9 +258,10 @@ describe('webpack loaders', () => {
});

describe('`distDir` value in default server-side `RewriteFrames` integration', () => {
describe('`RewriteFrames` ends up with correct `distDir` value', () => {
it('`RewriteFrames` ends up with correct `distDir` value', () => {
// TODO: this, along with any number of other parts of the build process, should be tested with an integration
// test which actually runs webpack and inspects the resulting bundles (and that integration test should test
// custom `distDir` values with and without a `.`, to make sure the regex escaping is working)
// custom `distDir` values with and without a `.`, to make sure the regex
// escaping is working)
});
});
21 changes: 15 additions & 6 deletions packages/nextjs/test/config/mocks.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { vi, afterAll, afterEach } from 'vitest';

vi.mock('fs');
vi.mock('os');

import { CLIENT_SDK_CONFIG_FILE, EDGE_SDK_CONFIG_FILE, SERVER_SDK_CONFIG_FILE } from './fixtures';

// We use `fs.existsSync()` in `getUserConfigFile()`. When we're not testing `getUserConfigFile()` specifically, all we
// need is for it to give us any valid answer, so make it always find what it's looking for. Since this is a core node
// built-in, though, which jest itself uses, otherwise let it do the normal thing. Storing the real version of the
// function also lets us restore the original when we do want to test `getUserConfigFile()`.
export const realExistsSync = jest.requireActual('fs').existsSync;
// function also lets us restore the original when we do want to test
// `getUserConfigFile()`.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const fsReal = (await vi.importActual('fs')) as typeof import('fs');
export const realExistsSync = fsReal.existsSync;
export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsSync> => {
if (
(path as string).endsWith(SERVER_SDK_CONFIG_FILE) ||
Expand All@@ -23,20 +30,22 @@ export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsS

return realExistsSync(path);
};
export const exitsSync = jest.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);
export const exitsSync = vi.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);

/** Mocking of temporary directory creation (so that we have a place to stick files (like `sentry.client.config.js`) in
* order to test that we can find them) */

// Make it so that all temporary folders, either created directly by tests or by the code they're testing, will go into
// one spot that we know about, which we can then clean up when we're done
const realTmpdir = jest.requireActual('os').tmpdir;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const osReal = (await vi.importActual('os')) as typeof import('os');
const realTmpdir = osReal.tmpdir;

// Including the random number ensures that even if multiple test files using these mocks are running at once, they have
// separate temporary folders
const TEMP_DIR_PATH = path.join(realTmpdir(), `sentry-nextjs-test-${Math.random()}`);

jest.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
vi.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
// In theory, we should always land in the `else` here, but this saves the cases where the prior run got interrupted and
// the `afterAll` below didn't happen.
if (fs.existsSync(TEMP_DIR_PATH)) {
Expand All@@ -52,7 +61,7 @@ afterAll(() => {
// In order to know what to expect in the webpack config `entry` property, we need to know the path of the temporary
// directory created when doing the file injection, so wrap the real `mkdtempSync` and store the resulting path where we
// can access it
export const mkdtempSyncSpy = jest.spyOn(fs, 'mkdtempSync');
export const mkdtempSyncSpy = vi.spyOn(fs, 'mkdtempSync');

afterEach(() => {
mkdtempSyncSpy.mockClear();
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/test/config/valueInjectionLoader.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { LoaderThis } from '../../src/config/loaders/types';
import type { ValueInjectionLoaderOptions } from '../../src/config/loaders/valueInjectionLoader';
import valueInjectionLoader from '../../src/config/loaders/valueInjectionLoader';
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, vi } from 'vitest';

// mock helper functions not tested directly in this file
import '../mocks';

Expand All@@ -12,9 +14,16 @@ import {
userNextConfig,
} from '../fixtures';
import { materializeFinalNextConfig, materializeFinalWebpackConfig } from '../testUtils';
import * as core from '@sentry/core';

describe('constructWebpackConfigFunction()', () => {
it('includes expected properties', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig,
incomingWebpackConfig: serverWebpackConfig,
Expand DownExpand Up@@ -46,7 +55,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => {
const getWebpackPluginOptionsSpy = jest.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
const getWebpackPluginOptionsSpy = vi.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

await materializeFinalWebpackConfig({
exportedNextConfig,
Expand DownExpand Up@@ -112,6 +126,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('uses `hidden-source-map` as `devtool` value for client-side builds', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalClientWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig: exportedNextConfig,
incomingWebpackConfig: clientWebpackConfig,
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { BuildContext, NextConfigObject } from '../../../src/config/types';
import { getWebpackPluginOptions } from '../../../src/config/webpackPluginOptions';

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
import * as SentryCore from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { describe, vi, beforeEach, afterEach, it, expect } from 'vitest';

import type { AugmentedNextApiResponse, NextApiHandler } from '../../src/common/types';
import { wrapApiHandlerWithSentry } from '../../src/server';

const startSpanManualSpy = jest.spyOn(SentryCore, 'startSpanManual');
const startSpanManualSpy = vi.spyOn(SentryCore, 'startSpanManual');

describe('withSentry', () => {
let req: NextApiRequest, res: NextApiResponse;
Expand All@@ -32,7 +33,7 @@ describe('withSentry', () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('tracing', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/test/config/withSentryConfig.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, vi, it, expect } from 'vitest';

import { defaultRuntimePhase, defaultsObject, exportedNextConfig, userNextConfig } from './fixtures';
import { materializeFinalNextConfig } from './testUtils';

Expand DownExpand Up@@ -43,7 +45,7 @@ describe('withSentryConfig', () => {
});

it('correctly passes `phase` and `defaultConfig` through to functional `userNextConfig`', () => {
const exportedNextConfigFunction = jest.fn().mockReturnValue(userNextConfig);
const exportedNextConfigFunction = vi.fn().mockReturnValue(userNextConfig);

materializeFinalNextConfig(exportedNextConfigFunction);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' test(nextjs): Migrate to Vitest by timfish · Pull Request #15546 · getsentry/sentry-javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions packages/nextjs/jest.config.js

This file was deleted.

4 changes: 2 additions & 2 deletions packages/nextjs/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -117,8 +117,8 @@
"lint": "eslint . --format stylish",
"test": "yarn test:unit",
"test:all": "run-s test:unit",
"test:unit": "jest",
"test:watch": "jest --watch",
"test:unit": "vitest run",
"test:watch": "vitest --watch",
"vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh",
"vercel:project": "source vercel/make-project-use-current-branch.sh",
"yalc:publish": "yalc publish --push --sig"
Expand Down
9 changes: 5 additions & 4 deletions packages/nextjs/test/clientSdk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import type { Integration } from '@sentry/core';
import * as SentryReact from '@sentry/react';
import { WINDOW, getClient, getCurrentScope } from '@sentry/react';
import { JSDOM } from 'jsdom';
import { describe, vi, afterAll, afterEach, it, expect } from 'vitest';

import { breadcrumbsIntegration, browserTracingIntegration, init } from '../src/client';

const reactInit = jest.spyOn(SentryReact, 'init');
const loggerLogSpy = jest.spyOn(logger, 'log');
const reactInit = vi.spyOn(SentryReact, 'init');
const loggerLogSpy = vi.spyOn(logger, 'log');

// We're setting up JSDom here because the Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
Expand DownExpand Up@@ -38,7 +39,7 @@ const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337';

describe('Client init()', () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();

getGlobalScope().clear();
getIsolationScope().clear();
Expand DownExpand Up@@ -83,7 +84,7 @@ describe('Client init()', () => {
dsn: 'https://dogsarebadatkeepingsecrets@squirrelchasers.ingest.sentry.io/12312012',
tracesSampleRate: 1.0,
});
const transportSend = jest.spyOn(getClient()!.getTransport()!, 'send');
const transportSend = vi.spyOn(getClient()!.getTransport()!, 'send');

// Ensure we have no current span, so our next span is a transaction
SentryReact.withActiveSpan(null, () => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`valueInjectionLoader should correctly insert values for basic config 1`] = `
exports[`valueInjectionLoader > should correctly insert values for basic config 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";import * as Sentry from '@sentry/nextjs';
;globalThis["foo"] = "bar";import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with a misplaced directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with a misplaced directive 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";console.log('This will render the directive useless');
\\"use client\\";
;globalThis["foo"] = "bar";console.log('This will render the directive useless');
"use client";



Expand All@@ -19,44 +19,44 @@ exports[`valueInjectionLoader should correctly insert values with a misplaced di
"
`;

exports[`valueInjectionLoader should correctly insert values with directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive 1`] = `
"
\\"use client\\";globalThis[\\"foo\\"] = \\"bar\\";
"use client";globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and block comments 1`] = `
"
/* test */
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and inline comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and inline comments 1`] = `
"
// test
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments 1`] = `
"
/*
test
*/
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
"
/*
test
Expand All@@ -65,7 +65,7 @@ exports[`valueInjectionLoader should correctly insert values with directive and



\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";



Expand All@@ -74,9 +74,9 @@ exports[`valueInjectionLoader should correctly insert values with directive and
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and semicolon 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and semicolon 1`] = `
"
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
Expand Down
42 changes: 8 additions & 34 deletions packages/nextjs/test/config/loaders.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
import './mocks';

import * as fs from 'fs';
import { describe, vi, it, expect } from 'vitest';

import type { ModuleRuleUseProperty, WebpackModuleRule } from '../../src/config/types';
import {
Expand All@@ -13,36 +14,8 @@ import {
} from './fixtures';
import { materializeFinalWebpackConfig } from './testUtils';

const existsSyncSpy = jest.spyOn(fs, 'existsSync');
const lstatSyncSpy = jest.spyOn(fs, 'lstatSync');

type MatcherResult = { pass: boolean; message: () => string };

expect.extend({
stringEndingWith(received: string, expectedEnding: string): MatcherResult {
const failsTest = !received.endsWith(expectedEnding);
const generateErrorMessage = () =>
failsTest
? // Regular error message for match failing
`expected string ending with '${expectedEnding}', but got '${received}'`
: // Error message for the match passing if someone has called it with `expect.not`
`expected string not ending with '${expectedEnding}', but got '${received}'`;

return {
pass: !failsTest,
message: generateErrorMessage,
};
},
});

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Expect {
stringEndingWith: (expectedEnding: string) => MatcherResult;
}
}
}
const existsSyncSpy = vi.spyOn(fs, 'existsSync');
const lstatSyncSpy = vi.spyOn(fs, 'lstatSync');

function applyRuleToResource(rule: WebpackModuleRule, resourcePath: string): ModuleRuleUseProperty[] {
const applications = [];
Expand DownExpand Up@@ -80,7 +53,7 @@ describe('webpack loaders', () => {
test: expect.any(RegExp),
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand DownExpand Up@@ -272,7 +245,7 @@ describe('webpack loaders', () => {
test: /sentry\.client\.config\.(jsx?|tsx?)/,
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand All@@ -285,9 +258,10 @@ describe('webpack loaders', () => {
});

describe('`distDir` value in default server-side `RewriteFrames` integration', () => {
describe('`RewriteFrames` ends up with correct `distDir` value', () => {
it('`RewriteFrames` ends up with correct `distDir` value', () => {
// TODO: this, along with any number of other parts of the build process, should be tested with an integration
// test which actually runs webpack and inspects the resulting bundles (and that integration test should test
// custom `distDir` values with and without a `.`, to make sure the regex escaping is working)
// custom `distDir` values with and without a `.`, to make sure the regex
// escaping is working)
});
});
21 changes: 15 additions & 6 deletions packages/nextjs/test/config/mocks.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { vi, afterAll, afterEach } from 'vitest';

vi.mock('fs');
vi.mock('os');

import { CLIENT_SDK_CONFIG_FILE, EDGE_SDK_CONFIG_FILE, SERVER_SDK_CONFIG_FILE } from './fixtures';

// We use `fs.existsSync()` in `getUserConfigFile()`. When we're not testing `getUserConfigFile()` specifically, all we
// need is for it to give us any valid answer, so make it always find what it's looking for. Since this is a core node
// built-in, though, which jest itself uses, otherwise let it do the normal thing. Storing the real version of the
// function also lets us restore the original when we do want to test `getUserConfigFile()`.
export const realExistsSync = jest.requireActual('fs').existsSync;
// function also lets us restore the original when we do want to test
// `getUserConfigFile()`.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const fsReal = (await vi.importActual('fs')) as typeof import('fs');
export const realExistsSync = fsReal.existsSync;
export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsSync> => {
if (
(path as string).endsWith(SERVER_SDK_CONFIG_FILE) ||
Expand All@@ -23,20 +30,22 @@ export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsS

return realExistsSync(path);
};
export const exitsSync = jest.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);
export const exitsSync = vi.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);

/** Mocking of temporary directory creation (so that we have a place to stick files (like `sentry.client.config.js`) in
* order to test that we can find them) */

// Make it so that all temporary folders, either created directly by tests or by the code they're testing, will go into
// one spot that we know about, which we can then clean up when we're done
const realTmpdir = jest.requireActual('os').tmpdir;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const osReal = (await vi.importActual('os')) as typeof import('os');
const realTmpdir = osReal.tmpdir;

// Including the random number ensures that even if multiple test files using these mocks are running at once, they have
// separate temporary folders
const TEMP_DIR_PATH = path.join(realTmpdir(), `sentry-nextjs-test-${Math.random()}`);

jest.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
vi.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
// In theory, we should always land in the `else` here, but this saves the cases where the prior run got interrupted and
// the `afterAll` below didn't happen.
if (fs.existsSync(TEMP_DIR_PATH)) {
Expand All@@ -52,7 +61,7 @@ afterAll(() => {
// In order to know what to expect in the webpack config `entry` property, we need to know the path of the temporary
// directory created when doing the file injection, so wrap the real `mkdtempSync` and store the resulting path where we
// can access it
export const mkdtempSyncSpy = jest.spyOn(fs, 'mkdtempSync');
export const mkdtempSyncSpy = vi.spyOn(fs, 'mkdtempSync');

afterEach(() => {
mkdtempSyncSpy.mockClear();
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/test/config/valueInjectionLoader.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { LoaderThis } from '../../src/config/loaders/types';
import type { ValueInjectionLoaderOptions } from '../../src/config/loaders/valueInjectionLoader';
import valueInjectionLoader from '../../src/config/loaders/valueInjectionLoader';
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, vi } from 'vitest';

// mock helper functions not tested directly in this file
import '../mocks';

Expand All@@ -12,9 +14,16 @@ import {
userNextConfig,
} from '../fixtures';
import { materializeFinalNextConfig, materializeFinalWebpackConfig } from '../testUtils';
import * as core from '@sentry/core';

describe('constructWebpackConfigFunction()', () => {
it('includes expected properties', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig,
incomingWebpackConfig: serverWebpackConfig,
Expand DownExpand Up@@ -46,7 +55,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => {
const getWebpackPluginOptionsSpy = jest.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
const getWebpackPluginOptionsSpy = vi.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

await materializeFinalWebpackConfig({
exportedNextConfig,
Expand DownExpand Up@@ -112,6 +126,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('uses `hidden-source-map` as `devtool` value for client-side builds', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalClientWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig: exportedNextConfig,
incomingWebpackConfig: clientWebpackConfig,
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { BuildContext, NextConfigObject } from '../../../src/config/types';
import { getWebpackPluginOptions } from '../../../src/config/webpackPluginOptions';

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
import * as SentryCore from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { describe, vi, beforeEach, afterEach, it, expect } from 'vitest';

import type { AugmentedNextApiResponse, NextApiHandler } from '../../src/common/types';
import { wrapApiHandlerWithSentry } from '../../src/server';

const startSpanManualSpy = jest.spyOn(SentryCore, 'startSpanManual');
const startSpanManualSpy = vi.spyOn(SentryCore, 'startSpanManual');

describe('withSentry', () => {
let req: NextApiRequest, res: NextApiResponse;
Expand All@@ -32,7 +33,7 @@ describe('withSentry', () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('tracing', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/test/config/withSentryConfig.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, vi, it, expect } from 'vitest';

import { defaultRuntimePhase, defaultsObject, exportedNextConfig, userNextConfig } from './fixtures';
import { materializeFinalNextConfig } from './testUtils';

Expand DownExpand Up@@ -43,7 +45,7 @@ describe('withSentryConfig', () => {
});

it('correctly passes `phase` and `defaultConfig` through to functional `userNextConfig`', () => {
const exportedNextConfigFunction = jest.fn().mockReturnValue(userNextConfig);
const exportedNextConfigFunction = vi.fn().mockReturnValue(userNextConfig);

materializeFinalNextConfig(exportedNextConfigFunction);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' test(nextjs): Migrate to Vitest by timfish · Pull Request #15546 · getsentry/sentry-javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions packages/nextjs/jest.config.js

This file was deleted.

4 changes: 2 additions & 2 deletions packages/nextjs/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -117,8 +117,8 @@
"lint": "eslint . --format stylish",
"test": "yarn test:unit",
"test:all": "run-s test:unit",
"test:unit": "jest",
"test:watch": "jest --watch",
"test:unit": "vitest run",
"test:watch": "vitest --watch",
"vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh",
"vercel:project": "source vercel/make-project-use-current-branch.sh",
"yalc:publish": "yalc publish --push --sig"
Expand Down
9 changes: 5 additions & 4 deletions packages/nextjs/test/clientSdk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import type { Integration } from '@sentry/core';
import * as SentryReact from '@sentry/react';
import { WINDOW, getClient, getCurrentScope } from '@sentry/react';
import { JSDOM } from 'jsdom';
import { describe, vi, afterAll, afterEach, it, expect } from 'vitest';

import { breadcrumbsIntegration, browserTracingIntegration, init } from '../src/client';

const reactInit = jest.spyOn(SentryReact, 'init');
const loggerLogSpy = jest.spyOn(logger, 'log');
const reactInit = vi.spyOn(SentryReact, 'init');
const loggerLogSpy = vi.spyOn(logger, 'log');

// We're setting up JSDom here because the Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
Expand DownExpand Up@@ -38,7 +39,7 @@ const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337';

describe('Client init()', () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();

getGlobalScope().clear();
getIsolationScope().clear();
Expand DownExpand Up@@ -83,7 +84,7 @@ describe('Client init()', () => {
dsn: 'https://dogsarebadatkeepingsecrets@squirrelchasers.ingest.sentry.io/12312012',
tracesSampleRate: 1.0,
});
const transportSend = jest.spyOn(getClient()!.getTransport()!, 'send');
const transportSend = vi.spyOn(getClient()!.getTransport()!, 'send');

// Ensure we have no current span, so our next span is a transaction
SentryReact.withActiveSpan(null, () => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`valueInjectionLoader should correctly insert values for basic config 1`] = `
exports[`valueInjectionLoader > should correctly insert values for basic config 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";import * as Sentry from '@sentry/nextjs';
;globalThis["foo"] = "bar";import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with a misplaced directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with a misplaced directive 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";console.log('This will render the directive useless');
\\"use client\\";
;globalThis["foo"] = "bar";console.log('This will render the directive useless');
"use client";



Expand All@@ -19,44 +19,44 @@ exports[`valueInjectionLoader should correctly insert values with a misplaced di
"
`;

exports[`valueInjectionLoader should correctly insert values with directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive 1`] = `
"
\\"use client\\";globalThis[\\"foo\\"] = \\"bar\\";
"use client";globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and block comments 1`] = `
"
/* test */
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and inline comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and inline comments 1`] = `
"
// test
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments 1`] = `
"
/*
test
*/
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
"
/*
test
Expand All@@ -65,7 +65,7 @@ exports[`valueInjectionLoader should correctly insert values with directive and



\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";



Expand All@@ -74,9 +74,9 @@ exports[`valueInjectionLoader should correctly insert values with directive and
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and semicolon 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and semicolon 1`] = `
"
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
Expand Down
42 changes: 8 additions & 34 deletions packages/nextjs/test/config/loaders.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
import './mocks';

import * as fs from 'fs';
import { describe, vi, it, expect } from 'vitest';

import type { ModuleRuleUseProperty, WebpackModuleRule } from '../../src/config/types';
import {
Expand All@@ -13,36 +14,8 @@ import {
} from './fixtures';
import { materializeFinalWebpackConfig } from './testUtils';

const existsSyncSpy = jest.spyOn(fs, 'existsSync');
const lstatSyncSpy = jest.spyOn(fs, 'lstatSync');

type MatcherResult = { pass: boolean; message: () => string };

expect.extend({
stringEndingWith(received: string, expectedEnding: string): MatcherResult {
const failsTest = !received.endsWith(expectedEnding);
const generateErrorMessage = () =>
failsTest
? // Regular error message for match failing
`expected string ending with '${expectedEnding}', but got '${received}'`
: // Error message for the match passing if someone has called it with `expect.not`
`expected string not ending with '${expectedEnding}', but got '${received}'`;

return {
pass: !failsTest,
message: generateErrorMessage,
};
},
});

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Expect {
stringEndingWith: (expectedEnding: string) => MatcherResult;
}
}
}
const existsSyncSpy = vi.spyOn(fs, 'existsSync');
const lstatSyncSpy = vi.spyOn(fs, 'lstatSync');

function applyRuleToResource(rule: WebpackModuleRule, resourcePath: string): ModuleRuleUseProperty[] {
const applications = [];
Expand DownExpand Up@@ -80,7 +53,7 @@ describe('webpack loaders', () => {
test: expect.any(RegExp),
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand DownExpand Up@@ -272,7 +245,7 @@ describe('webpack loaders', () => {
test: /sentry\.client\.config\.(jsx?|tsx?)/,
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand All@@ -285,9 +258,10 @@ describe('webpack loaders', () => {
});

describe('`distDir` value in default server-side `RewriteFrames` integration', () => {
describe('`RewriteFrames` ends up with correct `distDir` value', () => {
it('`RewriteFrames` ends up with correct `distDir` value', () => {
// TODO: this, along with any number of other parts of the build process, should be tested with an integration
// test which actually runs webpack and inspects the resulting bundles (and that integration test should test
// custom `distDir` values with and without a `.`, to make sure the regex escaping is working)
// custom `distDir` values with and without a `.`, to make sure the regex
// escaping is working)
});
});
21 changes: 15 additions & 6 deletions packages/nextjs/test/config/mocks.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { vi, afterAll, afterEach } from 'vitest';

vi.mock('fs');
vi.mock('os');

import { CLIENT_SDK_CONFIG_FILE, EDGE_SDK_CONFIG_FILE, SERVER_SDK_CONFIG_FILE } from './fixtures';

// We use `fs.existsSync()` in `getUserConfigFile()`. When we're not testing `getUserConfigFile()` specifically, all we
// need is for it to give us any valid answer, so make it always find what it's looking for. Since this is a core node
// built-in, though, which jest itself uses, otherwise let it do the normal thing. Storing the real version of the
// function also lets us restore the original when we do want to test `getUserConfigFile()`.
export const realExistsSync = jest.requireActual('fs').existsSync;
// function also lets us restore the original when we do want to test
// `getUserConfigFile()`.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const fsReal = (await vi.importActual('fs')) as typeof import('fs');
export const realExistsSync = fsReal.existsSync;
export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsSync> => {
if (
(path as string).endsWith(SERVER_SDK_CONFIG_FILE) ||
Expand All@@ -23,20 +30,22 @@ export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsS

return realExistsSync(path);
};
export const exitsSync = jest.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);
export const exitsSync = vi.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);

/** Mocking of temporary directory creation (so that we have a place to stick files (like `sentry.client.config.js`) in
* order to test that we can find them) */

// Make it so that all temporary folders, either created directly by tests or by the code they're testing, will go into
// one spot that we know about, which we can then clean up when we're done
const realTmpdir = jest.requireActual('os').tmpdir;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const osReal = (await vi.importActual('os')) as typeof import('os');
const realTmpdir = osReal.tmpdir;

// Including the random number ensures that even if multiple test files using these mocks are running at once, they have
// separate temporary folders
const TEMP_DIR_PATH = path.join(realTmpdir(), `sentry-nextjs-test-${Math.random()}`);

jest.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
vi.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
// In theory, we should always land in the `else` here, but this saves the cases where the prior run got interrupted and
// the `afterAll` below didn't happen.
if (fs.existsSync(TEMP_DIR_PATH)) {
Expand All@@ -52,7 +61,7 @@ afterAll(() => {
// In order to know what to expect in the webpack config `entry` property, we need to know the path of the temporary
// directory created when doing the file injection, so wrap the real `mkdtempSync` and store the resulting path where we
// can access it
export const mkdtempSyncSpy = jest.spyOn(fs, 'mkdtempSync');
export const mkdtempSyncSpy = vi.spyOn(fs, 'mkdtempSync');

afterEach(() => {
mkdtempSyncSpy.mockClear();
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/test/config/valueInjectionLoader.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { LoaderThis } from '../../src/config/loaders/types';
import type { ValueInjectionLoaderOptions } from '../../src/config/loaders/valueInjectionLoader';
import valueInjectionLoader from '../../src/config/loaders/valueInjectionLoader';
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, vi } from 'vitest';

// mock helper functions not tested directly in this file
import '../mocks';

Expand All@@ -12,9 +14,16 @@ import {
userNextConfig,
} from '../fixtures';
import { materializeFinalNextConfig, materializeFinalWebpackConfig } from '../testUtils';
import * as core from '@sentry/core';

describe('constructWebpackConfigFunction()', () => {
it('includes expected properties', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig,
incomingWebpackConfig: serverWebpackConfig,
Expand DownExpand Up@@ -46,7 +55,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => {
const getWebpackPluginOptionsSpy = jest.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
const getWebpackPluginOptionsSpy = vi.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

await materializeFinalWebpackConfig({
exportedNextConfig,
Expand DownExpand Up@@ -112,6 +126,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('uses `hidden-source-map` as `devtool` value for client-side builds', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalClientWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig: exportedNextConfig,
incomingWebpackConfig: clientWebpackConfig,
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { BuildContext, NextConfigObject } from '../../../src/config/types';
import { getWebpackPluginOptions } from '../../../src/config/webpackPluginOptions';

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
import * as SentryCore from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { describe, vi, beforeEach, afterEach, it, expect } from 'vitest';

import type { AugmentedNextApiResponse, NextApiHandler } from '../../src/common/types';
import { wrapApiHandlerWithSentry } from '../../src/server';

const startSpanManualSpy = jest.spyOn(SentryCore, 'startSpanManual');
const startSpanManualSpy = vi.spyOn(SentryCore, 'startSpanManual');

describe('withSentry', () => {
let req: NextApiRequest, res: NextApiResponse;
Expand All@@ -32,7 +33,7 @@ describe('withSentry', () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('tracing', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/test/config/withSentryConfig.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, vi, it, expect } from 'vitest';

import { defaultRuntimePhase, defaultsObject, exportedNextConfig, userNextConfig } from './fixtures';
import { materializeFinalNextConfig } from './testUtils';

Expand DownExpand Up@@ -43,7 +45,7 @@ describe('withSentryConfig', () => {
});

it('correctly passes `phase` and `defaultConfig` through to functional `userNextConfig`', () => {
const exportedNextConfigFunction = jest.fn().mockReturnValue(userNextConfig);
const exportedNextConfigFunction = vi.fn().mockReturnValue(userNextConfig);

materializeFinalNextConfig(exportedNextConfigFunction);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' test(nextjs): Migrate to Vitest by timfish · Pull Request #15546 · getsentry/sentry-javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions packages/nextjs/jest.config.js

This file was deleted.

4 changes: 2 additions & 2 deletions packages/nextjs/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -117,8 +117,8 @@
"lint": "eslint . --format stylish",
"test": "yarn test:unit",
"test:all": "run-s test:unit",
"test:unit": "jest",
"test:watch": "jest --watch",
"test:unit": "vitest run",
"test:watch": "vitest --watch",
"vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh",
"vercel:project": "source vercel/make-project-use-current-branch.sh",
"yalc:publish": "yalc publish --push --sig"
Expand Down
9 changes: 5 additions & 4 deletions packages/nextjs/test/clientSdk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import type { Integration } from '@sentry/core';
import * as SentryReact from '@sentry/react';
import { WINDOW, getClient, getCurrentScope } from '@sentry/react';
import { JSDOM } from 'jsdom';
import { describe, vi, afterAll, afterEach, it, expect } from 'vitest';

import { breadcrumbsIntegration, browserTracingIntegration, init } from '../src/client';

const reactInit = jest.spyOn(SentryReact, 'init');
const loggerLogSpy = jest.spyOn(logger, 'log');
const reactInit = vi.spyOn(SentryReact, 'init');
const loggerLogSpy = vi.spyOn(logger, 'log');

// We're setting up JSDom here because the Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
Expand DownExpand Up@@ -38,7 +39,7 @@ const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337';

describe('Client init()', () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();

getGlobalScope().clear();
getIsolationScope().clear();
Expand DownExpand Up@@ -83,7 +84,7 @@ describe('Client init()', () => {
dsn: 'https://dogsarebadatkeepingsecrets@squirrelchasers.ingest.sentry.io/12312012',
tracesSampleRate: 1.0,
});
const transportSend = jest.spyOn(getClient()!.getTransport()!, 'send');
const transportSend = vi.spyOn(getClient()!.getTransport()!, 'send');

// Ensure we have no current span, so our next span is a transaction
SentryReact.withActiveSpan(null, () => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`valueInjectionLoader should correctly insert values for basic config 1`] = `
exports[`valueInjectionLoader > should correctly insert values for basic config 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";import * as Sentry from '@sentry/nextjs';
;globalThis["foo"] = "bar";import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with a misplaced directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with a misplaced directive 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";console.log('This will render the directive useless');
\\"use client\\";
;globalThis["foo"] = "bar";console.log('This will render the directive useless');
"use client";



Expand All@@ -19,44 +19,44 @@ exports[`valueInjectionLoader should correctly insert values with a misplaced di
"
`;

exports[`valueInjectionLoader should correctly insert values with directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive 1`] = `
"
\\"use client\\";globalThis[\\"foo\\"] = \\"bar\\";
"use client";globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and block comments 1`] = `
"
/* test */
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and inline comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and inline comments 1`] = `
"
// test
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments 1`] = `
"
/*
test
*/
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
"
/*
test
Expand All@@ -65,7 +65,7 @@ exports[`valueInjectionLoader should correctly insert values with directive and



\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";



Expand All@@ -74,9 +74,9 @@ exports[`valueInjectionLoader should correctly insert values with directive and
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and semicolon 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and semicolon 1`] = `
"
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
Expand Down
42 changes: 8 additions & 34 deletions packages/nextjs/test/config/loaders.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
import './mocks';

import * as fs from 'fs';
import { describe, vi, it, expect } from 'vitest';

import type { ModuleRuleUseProperty, WebpackModuleRule } from '../../src/config/types';
import {
Expand All@@ -13,36 +14,8 @@ import {
} from './fixtures';
import { materializeFinalWebpackConfig } from './testUtils';

const existsSyncSpy = jest.spyOn(fs, 'existsSync');
const lstatSyncSpy = jest.spyOn(fs, 'lstatSync');

type MatcherResult = { pass: boolean; message: () => string };

expect.extend({
stringEndingWith(received: string, expectedEnding: string): MatcherResult {
const failsTest = !received.endsWith(expectedEnding);
const generateErrorMessage = () =>
failsTest
? // Regular error message for match failing
`expected string ending with '${expectedEnding}', but got '${received}'`
: // Error message for the match passing if someone has called it with `expect.not`
`expected string not ending with '${expectedEnding}', but got '${received}'`;

return {
pass: !failsTest,
message: generateErrorMessage,
};
},
});

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Expect {
stringEndingWith: (expectedEnding: string) => MatcherResult;
}
}
}
const existsSyncSpy = vi.spyOn(fs, 'existsSync');
const lstatSyncSpy = vi.spyOn(fs, 'lstatSync');

function applyRuleToResource(rule: WebpackModuleRule, resourcePath: string): ModuleRuleUseProperty[] {
const applications = [];
Expand DownExpand Up@@ -80,7 +53,7 @@ describe('webpack loaders', () => {
test: expect.any(RegExp),
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand DownExpand Up@@ -272,7 +245,7 @@ describe('webpack loaders', () => {
test: /sentry\.client\.config\.(jsx?|tsx?)/,
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand All@@ -285,9 +258,10 @@ describe('webpack loaders', () => {
});

describe('`distDir` value in default server-side `RewriteFrames` integration', () => {
describe('`RewriteFrames` ends up with correct `distDir` value', () => {
it('`RewriteFrames` ends up with correct `distDir` value', () => {
// TODO: this, along with any number of other parts of the build process, should be tested with an integration
// test which actually runs webpack and inspects the resulting bundles (and that integration test should test
// custom `distDir` values with and without a `.`, to make sure the regex escaping is working)
// custom `distDir` values with and without a `.`, to make sure the regex
// escaping is working)
});
});
21 changes: 15 additions & 6 deletions packages/nextjs/test/config/mocks.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { vi, afterAll, afterEach } from 'vitest';

vi.mock('fs');
vi.mock('os');

import { CLIENT_SDK_CONFIG_FILE, EDGE_SDK_CONFIG_FILE, SERVER_SDK_CONFIG_FILE } from './fixtures';

// We use `fs.existsSync()` in `getUserConfigFile()`. When we're not testing `getUserConfigFile()` specifically, all we
// need is for it to give us any valid answer, so make it always find what it's looking for. Since this is a core node
// built-in, though, which jest itself uses, otherwise let it do the normal thing. Storing the real version of the
// function also lets us restore the original when we do want to test `getUserConfigFile()`.
export const realExistsSync = jest.requireActual('fs').existsSync;
// function also lets us restore the original when we do want to test
// `getUserConfigFile()`.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const fsReal = (await vi.importActual('fs')) as typeof import('fs');
export const realExistsSync = fsReal.existsSync;
export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsSync> => {
if (
(path as string).endsWith(SERVER_SDK_CONFIG_FILE) ||
Expand All@@ -23,20 +30,22 @@ export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsS

return realExistsSync(path);
};
export const exitsSync = jest.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);
export const exitsSync = vi.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);

/** Mocking of temporary directory creation (so that we have a place to stick files (like `sentry.client.config.js`) in
* order to test that we can find them) */

// Make it so that all temporary folders, either created directly by tests or by the code they're testing, will go into
// one spot that we know about, which we can then clean up when we're done
const realTmpdir = jest.requireActual('os').tmpdir;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const osReal = (await vi.importActual('os')) as typeof import('os');
const realTmpdir = osReal.tmpdir;

// Including the random number ensures that even if multiple test files using these mocks are running at once, they have
// separate temporary folders
const TEMP_DIR_PATH = path.join(realTmpdir(), `sentry-nextjs-test-${Math.random()}`);

jest.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
vi.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
// In theory, we should always land in the `else` here, but this saves the cases where the prior run got interrupted and
// the `afterAll` below didn't happen.
if (fs.existsSync(TEMP_DIR_PATH)) {
Expand All@@ -52,7 +61,7 @@ afterAll(() => {
// In order to know what to expect in the webpack config `entry` property, we need to know the path of the temporary
// directory created when doing the file injection, so wrap the real `mkdtempSync` and store the resulting path where we
// can access it
export const mkdtempSyncSpy = jest.spyOn(fs, 'mkdtempSync');
export const mkdtempSyncSpy = vi.spyOn(fs, 'mkdtempSync');

afterEach(() => {
mkdtempSyncSpy.mockClear();
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/test/config/valueInjectionLoader.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { LoaderThis } from '../../src/config/loaders/types';
import type { ValueInjectionLoaderOptions } from '../../src/config/loaders/valueInjectionLoader';
import valueInjectionLoader from '../../src/config/loaders/valueInjectionLoader';
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, vi } from 'vitest';

// mock helper functions not tested directly in this file
import '../mocks';

Expand All@@ -12,9 +14,16 @@ import {
userNextConfig,
} from '../fixtures';
import { materializeFinalNextConfig, materializeFinalWebpackConfig } from '../testUtils';
import * as core from '@sentry/core';

describe('constructWebpackConfigFunction()', () => {
it('includes expected properties', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig,
incomingWebpackConfig: serverWebpackConfig,
Expand DownExpand Up@@ -46,7 +55,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => {
const getWebpackPluginOptionsSpy = jest.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
const getWebpackPluginOptionsSpy = vi.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

await materializeFinalWebpackConfig({
exportedNextConfig,
Expand DownExpand Up@@ -112,6 +126,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('uses `hidden-source-map` as `devtool` value for client-side builds', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalClientWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig: exportedNextConfig,
incomingWebpackConfig: clientWebpackConfig,
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { BuildContext, NextConfigObject } from '../../../src/config/types';
import { getWebpackPluginOptions } from '../../../src/config/webpackPluginOptions';

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
import * as SentryCore from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { describe, vi, beforeEach, afterEach, it, expect } from 'vitest';

import type { AugmentedNextApiResponse, NextApiHandler } from '../../src/common/types';
import { wrapApiHandlerWithSentry } from '../../src/server';

const startSpanManualSpy = jest.spyOn(SentryCore, 'startSpanManual');
const startSpanManualSpy = vi.spyOn(SentryCore, 'startSpanManual');

describe('withSentry', () => {
let req: NextApiRequest, res: NextApiResponse;
Expand All@@ -32,7 +33,7 @@ describe('withSentry', () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('tracing', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/test/config/withSentryConfig.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, vi, it, expect } from 'vitest';

import { defaultRuntimePhase, defaultsObject, exportedNextConfig, userNextConfig } from './fixtures';
import { materializeFinalNextConfig } from './testUtils';

Expand DownExpand Up@@ -43,7 +45,7 @@ describe('withSentryConfig', () => {
});

it('correctly passes `phase` and `defaultConfig` through to functional `userNextConfig`', () => {
const exportedNextConfigFunction = jest.fn().mockReturnValue(userNextConfig);
const exportedNextConfigFunction = vi.fn().mockReturnValue(userNextConfig);

materializeFinalNextConfig(exportedNextConfigFunction);

Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); test(nextjs): Migrate to Vitest by timfish · Pull Request #15546 · getsentry/sentry-javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions packages/nextjs/jest.config.js

This file was deleted.

4 changes: 2 additions & 2 deletions packages/nextjs/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -117,8 +117,8 @@
"lint": "eslint . --format stylish",
"test": "yarn test:unit",
"test:all": "run-s test:unit",
"test:unit": "jest",
"test:watch": "jest --watch",
"test:unit": "vitest run",
"test:watch": "vitest --watch",
"vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh",
"vercel:project": "source vercel/make-project-use-current-branch.sh",
"yalc:publish": "yalc publish --push --sig"
Expand Down
9 changes: 5 additions & 4 deletions packages/nextjs/test/clientSdk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,12 @@ import type { Integration } from '@sentry/core';
import * as SentryReact from '@sentry/react';
import { WINDOW, getClient, getCurrentScope } from '@sentry/react';
import { JSDOM } from 'jsdom';
import { describe, vi, afterAll, afterEach, it, expect } from 'vitest';

import { breadcrumbsIntegration, browserTracingIntegration, init } from '../src/client';

const reactInit = jest.spyOn(SentryReact, 'init');
const loggerLogSpy = jest.spyOn(logger, 'log');
const reactInit = vi.spyOn(SentryReact, 'init');
const loggerLogSpy = vi.spyOn(logger, 'log');

// We're setting up JSDom here because the Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
Expand DownExpand Up@@ -38,7 +39,7 @@ const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337';

describe('Client init()', () => {
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();

getGlobalScope().clear();
getIsolationScope().clear();
Expand DownExpand Up@@ -83,7 +84,7 @@ describe('Client init()', () => {
dsn: 'https://dogsarebadatkeepingsecrets@squirrelchasers.ingest.sentry.io/12312012',
tracesSampleRate: 1.0,
});
const transportSend = jest.spyOn(getClient()!.getTransport()!, 'send');
const transportSend = vi.spyOn(getClient()!.getTransport()!, 'send');

// Ensure we have no current span, so our next span is a transaction
SentryReact.withActiveSpan(null, () => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`valueInjectionLoader should correctly insert values for basic config 1`] = `
exports[`valueInjectionLoader > should correctly insert values for basic config 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";import * as Sentry from '@sentry/nextjs';
;globalThis["foo"] = "bar";import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with a misplaced directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with a misplaced directive 1`] = `
"
;globalThis[\\"foo\\"] = \\"bar\\";console.log('This will render the directive useless');
\\"use client\\";
;globalThis["foo"] = "bar";console.log('This will render the directive useless');
"use client";



Expand All@@ -19,44 +19,44 @@ exports[`valueInjectionLoader should correctly insert values with a misplaced di
"
`;

exports[`valueInjectionLoader should correctly insert values with directive 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive 1`] = `
"
\\"use client\\";globalThis[\\"foo\\"] = \\"bar\\";
"use client";globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and block comments 1`] = `
"
/* test */
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and inline comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and inline comments 1`] = `
"
// test
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments 1`] = `
"
/*
test
*/
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and multiline block comments and a bunch of whitespace 1`] = `
"
/*
test
Expand All@@ -65,7 +65,7 @@ exports[`valueInjectionLoader should correctly insert values with directive and



\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";



Expand All@@ -74,9 +74,9 @@ exports[`valueInjectionLoader should correctly insert values with directive and
"
`;

exports[`valueInjectionLoader should correctly insert values with directive and semicolon 1`] = `
exports[`valueInjectionLoader > should correctly insert values with directive and semicolon 1`] = `
"
\\"use client\\";;globalThis[\\"foo\\"] = \\"bar\\";
"use client";;globalThis["foo"] = "bar";
import * as Sentry from '@sentry/nextjs';
Sentry.init();
"
Expand Down
42 changes: 8 additions & 34 deletions packages/nextjs/test/config/loaders.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
import './mocks';

import * as fs from 'fs';
import { describe, vi, it, expect } from 'vitest';

import type { ModuleRuleUseProperty, WebpackModuleRule } from '../../src/config/types';
import {
Expand All@@ -13,36 +14,8 @@ import {
} from './fixtures';
import { materializeFinalWebpackConfig } from './testUtils';

const existsSyncSpy = jest.spyOn(fs, 'existsSync');
const lstatSyncSpy = jest.spyOn(fs, 'lstatSync');

type MatcherResult = { pass: boolean; message: () => string };

expect.extend({
stringEndingWith(received: string, expectedEnding: string): MatcherResult {
const failsTest = !received.endsWith(expectedEnding);
const generateErrorMessage = () =>
failsTest
? // Regular error message for match failing
`expected string ending with '${expectedEnding}', but got '${received}'`
: // Error message for the match passing if someone has called it with `expect.not`
`expected string not ending with '${expectedEnding}', but got '${received}'`;

return {
pass: !failsTest,
message: generateErrorMessage,
};
},
});

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Expect {
stringEndingWith: (expectedEnding: string) => MatcherResult;
}
}
}
const existsSyncSpy = vi.spyOn(fs, 'existsSync');
const lstatSyncSpy = vi.spyOn(fs, 'lstatSync');

function applyRuleToResource(rule: WebpackModuleRule, resourcePath: string): ModuleRuleUseProperty[] {
const applications = [];
Expand DownExpand Up@@ -80,7 +53,7 @@ describe('webpack loaders', () => {
test: expect.any(RegExp),
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand DownExpand Up@@ -272,7 +245,7 @@ describe('webpack loaders', () => {
test: /sentry\.client\.config\.(jsx?|tsx?)/,
use: [
{
loader: expect.stringEndingWith('valueInjectionLoader.js'),
loader: expect.stringMatching(/valueInjectionLoader\.js$/),
// We use `expect.objectContaining({})` rather than `expect.any(Object)` to match any plain object because
// the latter will also match arrays, regexes, dates, sets, etc. - anything whose `typeof` value is
// `'object'`.
Expand All@@ -285,9 +258,10 @@ describe('webpack loaders', () => {
});

describe('`distDir` value in default server-side `RewriteFrames` integration', () => {
describe('`RewriteFrames` ends up with correct `distDir` value', () => {
it('`RewriteFrames` ends up with correct `distDir` value', () => {
// TODO: this, along with any number of other parts of the build process, should be tested with an integration
// test which actually runs webpack and inspects the resulting bundles (and that integration test should test
// custom `distDir` values with and without a `.`, to make sure the regex escaping is working)
// custom `distDir` values with and without a `.`, to make sure the regex
// escaping is working)
});
});
21 changes: 15 additions & 6 deletions packages/nextjs/test/config/mocks.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,14 +4,21 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { vi, afterAll, afterEach } from 'vitest';

vi.mock('fs');
vi.mock('os');

import { CLIENT_SDK_CONFIG_FILE, EDGE_SDK_CONFIG_FILE, SERVER_SDK_CONFIG_FILE } from './fixtures';

// We use `fs.existsSync()` in `getUserConfigFile()`. When we're not testing `getUserConfigFile()` specifically, all we
// need is for it to give us any valid answer, so make it always find what it's looking for. Since this is a core node
// built-in, though, which jest itself uses, otherwise let it do the normal thing. Storing the real version of the
// function also lets us restore the original when we do want to test `getUserConfigFile()`.
export const realExistsSync = jest.requireActual('fs').existsSync;
// function also lets us restore the original when we do want to test
// `getUserConfigFile()`.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const fsReal = (await vi.importActual('fs')) as typeof import('fs');
export const realExistsSync = fsReal.existsSync;
export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsSync> => {
if (
(path as string).endsWith(SERVER_SDK_CONFIG_FILE) ||
Expand All@@ -23,20 +30,22 @@ export const mockExistsSync = (path: fs.PathLike): ReturnType<typeof realExistsS

return realExistsSync(path);
};
export const exitsSync = jest.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);
export const exitsSync = vi.spyOn(fs, 'existsSync').mockImplementation(mockExistsSync);

/** Mocking of temporary directory creation (so that we have a place to stick files (like `sentry.client.config.js`) in
* order to test that we can find them) */

// Make it so that all temporary folders, either created directly by tests or by the code they're testing, will go into
// one spot that we know about, which we can then clean up when we're done
const realTmpdir = jest.requireActual('os').tmpdir;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const osReal = (await vi.importActual('os')) as typeof import('os');
const realTmpdir = osReal.tmpdir;

// Including the random number ensures that even if multiple test files using these mocks are running at once, they have
// separate temporary folders
const TEMP_DIR_PATH = path.join(realTmpdir(), `sentry-nextjs-test-${Math.random()}`);

jest.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
vi.spyOn(os, 'tmpdir').mockReturnValue(TEMP_DIR_PATH);
// In theory, we should always land in the `else` here, but this saves the cases where the prior run got interrupted and
// the `afterAll` below didn't happen.
if (fs.existsSync(TEMP_DIR_PATH)) {
Expand All@@ -52,7 +61,7 @@ afterAll(() => {
// In order to know what to expect in the webpack config `entry` property, we need to know the path of the temporary
// directory created when doing the file injection, so wrap the real `mkdtempSync` and store the resulting path where we
// can access it
export const mkdtempSyncSpy = jest.spyOn(fs, 'mkdtempSync');
export const mkdtempSyncSpy = vi.spyOn(fs, 'mkdtempSync');

afterEach(() => {
mkdtempSyncSpy.mockClear();
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/test/config/valueInjectionLoader.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { LoaderThis } from '../../src/config/loaders/types';
import type { ValueInjectionLoaderOptions } from '../../src/config/loaders/valueInjectionLoader';
import valueInjectionLoader from '../../src/config/loaders/valueInjectionLoader';
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, vi } from 'vitest';

// mock helper functions not tested directly in this file
import '../mocks';

Expand All@@ -12,9 +14,16 @@ import {
userNextConfig,
} from '../fixtures';
import { materializeFinalNextConfig, materializeFinalWebpackConfig } from '../testUtils';
import * as core from '@sentry/core';

describe('constructWebpackConfigFunction()', () => {
it('includes expected properties', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig,
incomingWebpackConfig: serverWebpackConfig,
Expand DownExpand Up@@ -46,7 +55,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('automatically enables deleteSourcemapsAfterUpload for client builds when not explicitly set', async () => {
const getWebpackPluginOptionsSpy = jest.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
const getWebpackPluginOptionsSpy = vi.spyOn(getWebpackPluginOptionsModule, 'getWebpackPluginOptions');
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

await materializeFinalWebpackConfig({
exportedNextConfig,
Expand DownExpand Up@@ -112,6 +126,12 @@ describe('constructWebpackConfigFunction()', () => {
});

it('uses `hidden-source-map` as `devtool` value for client-side builds', async () => {
vi.spyOn(core, 'loadModule').mockImplementation(() => ({
sentryWebpackPlugin: () => ({
_name: 'sentry-webpack-plugin',
}),
}));

const finalClientWebpackConfig = await materializeFinalWebpackConfig({
exportedNextConfig: exportedNextConfig,
incomingWebpackConfig: clientWebpackConfig,
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import type { BuildContext, NextConfigObject } from '../../../src/config/types';
import { getWebpackPluginOptions } from '../../../src/config/webpackPluginOptions';

Expand Down
5 changes: 3 additions & 2 deletions packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
import * as SentryCore from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { describe, vi, beforeEach, afterEach, it, expect } from 'vitest';

import type { AugmentedNextApiResponse, NextApiHandler } from '../../src/common/types';
import { wrapApiHandlerWithSentry } from '../../src/server';

const startSpanManualSpy = jest.spyOn(SentryCore, 'startSpanManual');
const startSpanManualSpy = vi.spyOn(SentryCore, 'startSpanManual');

describe('withSentry', () => {
let req: NextApiRequest, res: NextApiResponse;
Expand All@@ -32,7 +33,7 @@ describe('withSentry', () => {
});

afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('tracing', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/test/config/withSentryConfig.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
import { describe, vi, it, expect } from 'vitest';

import { defaultRuntimePhase, defaultsObject, exportedNextConfig, userNextConfig } from './fixtures';
import { materializeFinalNextConfig } from './testUtils';

Expand DownExpand Up@@ -43,7 +45,7 @@ describe('withSentryConfig', () => {
});

it('correctly passes `phase` and `defaultConfig` through to functional `userNextConfig`', () => {
const exportedNextConfigFunction = jest.fn().mockReturnValue(userNextConfig);
const exportedNextConfigFunction = vi.fn().mockReturnValue(userNextConfig);

materializeFinalNextConfig(exportedNextConfigFunction);

Expand Down
Loading