Skip to content
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

fix: support duplicate installations #50

Merged
merged 2 commits into from
Oct 12, 2023
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jest-metadata",
"version": "1.0.0-beta.23",
"version": "1.0.0",
"description": "Extend Jest with custom metadata",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
17 changes: 15 additions & 2 deletions src/realms/detect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,25 @@ export function isJestWorker(): boolean {
return 'JEST_WORKER_ID' in process.env;
}

export function injectRealmIntoSandbox(sandbox: any, realm: ProcessRealm): void {
export function injectRealmIntoSandbox(sandbox: any, realm: ProcessRealm): ProcessRealm {
sandbox.__JEST_METADATA__ = realm;
if (sandbox !== globalThis) {
sandbox.__JEST_METADATA_SANDBOX__ = true;
}

return realm;
}

export function getSandboxedRealm(): ProcessRealm | undefined {
return (global as any).__JEST_METADATA__;
const globalAny = globalThis as any;
const realm = globalAny.__JEST_METADATA__;
if (realm && !globalAny.__JEST_METADATA_SANDBOX__) {
console.warn(
'[jest-metadata] Detected duplicate jest-metadata package in the same process. This may lead to unexpected behavior.',
);
}

return realm;
}

export function getServerId(): string | undefined {
Expand Down
4 changes: 2 additions & 2 deletions src/realms/realm.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-var-requires,node/no-missing-require */
// TODO: think about ESM support via dynamic import
import { getSandboxedRealm, isClient } from './detect';
import { getSandboxedRealm, injectRealmIntoSandbox, isClient } from './detect';
import type { ProcessRealm } from './ProcessRealm';

function createRealm(): ProcessRealm {
Expand All @@ -13,4 +13,4 @@ function createRealm(): ProcessRealm {
}
}

export default getSandboxedRealm() ?? createRealm();
export default getSandboxedRealm() ?? injectRealmIntoSandbox(globalThis, createRealm());