Skip to content

test(utils): Switch to using vitest #12959

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
9 changes: 0 additions & 9 deletions packages/utils/jest.config.js

This file was deleted.

7 changes: 3 additions & 4 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@
"@sentry/types": "8.20.0"
},
"devDependencies": {
"@types/array.prototype.flat": "^1.2.1",
"array.prototype.flat": "^1.3.0"
"vitest": "^0.31.4"
},
"scripts": {
"build": "run-p build:transpile build:types",
Expand All @@ -61,8 +60,8 @@
"clean": "rimraf build coverage cjs esm sentry-utils-*.tgz",
"fix": "eslint . --format stylish --fix",
"lint": "eslint . --format stylish",
"test": "jest",
"test:watch": "jest --watch",
"test": "vitest run",
"test:watch": "vitest --watch",
"version": "node ../../scripts/versionbump.js src/version.ts",
"yalc:publish": "yalc publish --push --sig"
},
Expand Down
3 changes: 2 additions & 1 deletion packages/utils/src/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,9 @@ export function addNonEnumerableProperty(obj: object, name: string, value: unkno
export function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {
try {
const proto = original.prototype || {};
wrapped.prototype = original.prototype = proto;
wrapped.prototype = proto;
addNonEnumerableProperty(wrapped, '__sentry_original__', original);
original.prototype = proto;
} catch (o_O) {} // eslint-disable-line no-empty
}

Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/aggregate-errors.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect } from 'vitest';

import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';

import { applyAggregateErrorsToEvent, createStackParser } from '../src/index';
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/array.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, it } from 'vitest';

import type { NestedArray } from '../src/array';
import { flatten } from '../src/array';

Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/baggage.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { expect, test } from 'vitest';

import { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../src/baggage';

test.each([
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/browser.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { beforeAll, beforeEach, describe, expect, it } from 'vitest';

import { JSDOM } from 'jsdom';

import { getDomElement, htmlTreeAsString } from '../src/browser';
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/buildPolyfills/nullishCoalesce.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, it } from 'vitest';

import { _nullishCoalesce } from '../../src/buildPolyfills';
import type { Value } from '../../src/buildPolyfills/types';
import { _nullishCoalesce as _nullishCoalesceOrig } from './originals';
Expand Down
6 changes: 1 addition & 5 deletions packages/utils/test/buildPolyfills/optionalChain.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import { default as arrayFlat } from 'array.prototype.flat';
import { describe, expect, it } from 'vitest';

import { _optionalChain } from '../../src/buildPolyfills';
import type { GenericFunction, GenericObject, Value } from '../../src/buildPolyfills/types';
import { _optionalChain as _optionalChainOrig } from './originals';

// Older versions of Node don't have `Array.prototype.flat`, which crashes these tests. On newer versions that do have
// it, this is a no-op.
arrayFlat.shim();

type OperationType = 'access' | 'call' | 'optionalAccess' | 'optionalCall';
type OperationExecutor =
| ((intermediateValue: GenericObject) => Value)
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/clientreport.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, it } from 'vitest';

import type { ClientReport } from '@sentry/types';

import { createClientReportEnvelope } from '../src/clientreport';
Expand Down
1 change: 1 addition & 0 deletions packages/utils/test/cookie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { describe, expect, it } from 'vitest';

import { parseCookie } from '../src/cookie';

Expand Down
10 changes: 6 additions & 4 deletions packages/utils/test/dsn.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { beforeEach, describe, expect, test, vi } from 'vitest';

import { DEBUG_BUILD } from '../src/debug-build';
import { dsnToString, makeDsn } from '../src/dsn';
import { logger } from '../src/logger';

function testIf(condition: boolean): jest.It {
function testIf(condition: boolean) {
return condition ? test : test.skip;
}

const loggerErrorSpy = jest.spyOn(logger, 'error').mockImplementation(() => {});
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
const loggerErrorSpy = vi.spyOn(logger, 'error').mockImplementation(() => {});
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

describe('Dsn', () => {
beforeEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});

describe('fromComponents', () => {
Expand Down
10 changes: 4 additions & 6 deletions packages/utils/test/envelope.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { afterEach, describe, expect, it, test, vi } from 'vitest';

import type { Event, EventEnvelope, SpanAttributes } from '@sentry/types';

import {
Expand Down Expand Up @@ -108,12 +110,8 @@ describe('envelope', () => {
name: 'with TextEncoder/Decoder polyfill',
before: () => {
GLOBAL_OBJ.__SENTRY__ = {} as InternalGlobal['__SENTRY__'];
GLOBAL_OBJ.__SENTRY__.encodePolyfill = jest.fn<Uint8Array, [string]>((input: string) =>
new TextEncoder().encode(input),
);
GLOBAL_OBJ.__SENTRY__.decodePolyfill = jest.fn<string, [Uint8Array]>((input: Uint8Array) =>
new TextDecoder().decode(input),
);
GLOBAL_OBJ.__SENTRY__.encodePolyfill = vi.fn((input: string) => new TextEncoder().encode(input));
GLOBAL_OBJ.__SENTRY__.decodePolyfill = vi.fn((input: Uint8Array) => new TextDecoder().decode(input));
},
after: () => {
expect(GLOBAL_OBJ.__SENTRY__.encodePolyfill).toHaveBeenCalled();
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/eventbuilder.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, test } from 'vitest';

import type { Client } from '@sentry/types';

import { createStackParser, eventFromUnknownInput, nodeStackLineParser } from '../src';
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/instrument/fetch.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, it } from 'vitest';

import { parseFetchArgs } from '../../src/instrument/fetch';

describe('instrument > parseFetchArgs', () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/is.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, it, test } from 'vitest';

import {
isDOMError,
isDOMException,
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/lru.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, test } from 'vitest';

import { LRUMap } from '../src/lru';

describe('LRUMap', () => {
Expand Down
73 changes: 46 additions & 27 deletions packages/utils/test/misc.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { afterEach, describe, expect, it, test, vi } from 'vitest';

import * as cryptoMod from 'node:crypto';

import type { Event, Mechanism, StackFrame } from '@sentry/types';

import {
Expand All @@ -6,9 +10,26 @@ import {
arrayify,
checkOrSetAlreadyCaught,
getEventDescription,
parseSemver,
uuid4,
} from '../src/misc';

const NODE_VERSION = parseSemver(process.versions.node);
/**
* Returns`describe` or `describe.skip` depending on allowed major versions of Node.
*
* @param {{ min?: number; max?: number }} allowedVersion
*/
export const conditionalTest = (allowedVersion: { min?: number; max?: number }) => {
if (!NODE_VERSION) {
return test.skip;
}

return NODE_VERSION < (allowedVersion.min || -Infinity) || NODE_VERSION > (allowedVersion.max || Infinity)
? test.skip
: test;
};

describe('getEventDescription()', () => {
test('message event', () => {
expect(
Expand Down Expand Up @@ -290,6 +311,10 @@ describe('checkOrSetAlreadyCaught()', () => {
});

describe('uuid4 generation', () => {
afterEach(() => {
vi.unstubAllGlobals();
});

const uuid4Regex = /^[0-9A-F]{12}[4][0-9A-F]{3}[89AB][0-9A-F]{15}$/i;
// Jest messes with the global object, so there is no global crypto object in any node version
// For this reason we need to create our own crypto object for each test to cover all the code paths
Expand All @@ -299,45 +324,39 @@ describe('uuid4 generation', () => {
}
});

it('returns valid uuid v4 ids via crypto.getRandomValues', () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cryptoMod = require('crypto');

(global as any).crypto = { getRandomValues: cryptoMod.getRandomValues };
conditionalTest({ min: 17 })('returns valid uuid v4 ids via crypto.getRandomValues', () => {
vi.stubGlobal('crypto', { getRandomValues: (cryptoMod as any).getRandomValues });

for (let index = 0; index < 1_000; index++) {
expect(uuid4()).toMatch(uuid4Regex);
}
});

it('returns valid uuid v4 ids via crypto.randomUUID', () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cryptoMod = require('crypto');

(global as any).crypto = { randomUUID: cryptoMod.randomUUID };
vi.stubGlobal('crypto', { getRandomValues: cryptoMod.randomUUID });

for (let index = 0; index < 1_000; index++) {
expect(uuid4()).toMatch(uuid4Regex);
}
});

it("return valid uuid v4 even if crypto doesn't exists", () => {
(global as any).crypto = { getRandomValues: undefined, randomUUID: undefined };
vi.stubGlobal('crypto', { getRandomValues: undefined, randomUUID: undefined });

for (let index = 0; index < 1_000; index++) {
expect(uuid4()).toMatch(uuid4Regex);
}
});

it('return valid uuid v4 even if crypto invoked causes an error', () => {
(global as any).crypto = {
vi.stubGlobal('crypto', {
getRandomValues: () => {
throw new Error('yo');
},
randomUUID: () => {
throw new Error('yo');
},
};
});

for (let index = 0; index < 1_000; index++) {
expect(uuid4()).toMatch(uuid4Regex);
Expand All @@ -346,22 +365,22 @@ describe('uuid4 generation', () => {

// Corner case related to crypto.getRandomValues being only
// semi-implemented (e.g. Chromium 23.0.1235.0 (151422))
it('returns valid uuid v4 even if crypto.getRandomValues does not return a typed array', () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cryptoMod = require('crypto');

const getRandomValues = (typedArray: Uint8Array) => {
if (cryptoMod.getRandomValues) {
cryptoMod.getRandomValues(typedArray);
conditionalTest({ min: 17 })(
'returns valid uuid v4 even if crypto.getRandomValues does not return a typed array',
() => {
const getRandomValues = (typedArray: Uint8Array) => {
if ((cryptoMod as any).getRandomValues) {
(cryptoMod as any).getRandomValues(typedArray);
}
};

vi.stubGlobal('crypto', { getRandomValues });

for (let index = 0; index < 1_000; index++) {
expect(uuid4()).toMatch(uuid4Regex);
}
};

(global as any).crypto = { getRandomValues };

for (let index = 0; index < 1_000; index++) {
expect(uuid4()).toMatch(uuid4Regex);
}
});
},
);
});

describe('arrayify()', () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/utils/test/normalize-url.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, expect, it } from 'vitest';

import { normalizeUrlToBase } from '../src/normalize';

describe('normalizeUrlToBase()', () => {
Expand Down
10 changes: 6 additions & 4 deletions packages/utils/test/normalize.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/**
* @jest-environment jsdom
* @vitest-environment jsdom
*/

import { describe, expect, test, vi } from 'vitest';

import * as isModule from '../src/is';
import { normalize } from '../src/normalize';
import { addNonEnumerableProperty } from '../src/object';
Expand Down Expand Up @@ -49,8 +51,8 @@ describe('normalize()', () => {
});
});

describe('extracts data from `Event` objects', () => {
const isElement = jest.spyOn(isModule, 'isElement').mockReturnValue(true);
test('extracts data from `Event` objects', () => {
const isElement = vi.spyOn(isModule, 'isElement').mockReturnValue(true);
const getAttribute = () => undefined;

const parkElement = { tagName: 'PARK', getAttribute };
Expand Down Expand Up @@ -593,7 +595,7 @@ describe('normalize()', () => {

describe('handles serialization errors', () => {
test('restricts effect of error to problematic node', () => {
jest.spyOn(stacktraceModule, 'getFunctionName').mockImplementationOnce(() => {
vi.spyOn(stacktraceModule, 'getFunctionName').mockImplementationOnce(() => {
throw new Error('Nope');
});

Expand Down
Loading
Loading