Skip to content

Commit

Permalink
mock: actually be resilient against multiple instances
Browse files Browse the repository at this point in the history
Making the service key a global works only as long as there's
exactly one instance of this module in the tree.

Which, probably always going to be the case. But still. Better
to actually not have that be an issue.
  • Loading branch information
isaacs committed Sep 15, 2023
1 parent 2c135b0 commit 556e520
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 18 deletions.
3 changes: 2 additions & 1 deletion src/mock/.tshy/commonjs.json
Expand Up @@ -6,7 +6,8 @@
"../src/**/*.tsx"
],
"exclude": [
".../src/**/*.mts"
".../src/**/*.mts",
"../src/service-key.ts"
],
"compilerOptions": {
"outDir": "../.tshy-build-tmp/commonjs"
Expand Down
20 changes: 3 additions & 17 deletions src/mock/src/service-key.ts
@@ -1,17 +1,3 @@
import { randomBytes } from 'crypto'

// Need this to be the same for a given thread between both
// CJS and ESM, since it might be loaded in the main thread via
// the import.mjs (esm), the globalPreload script (cjs), and of course the
// user's test program.
const kServiceKey = Symbol.for('@tapjs/mock.globalServiceKey')
const g = globalThis as typeof globalThis & {
[kServiceKey]?: string
}

// literally the only way to cover both branches would be to break
// mocking entirely, so ignore this.
export const serviceKey = (g[kServiceKey] =
/* c8 ignore start */
g[kServiceKey] ?? randomBytes(8).toString('hex'))
/* c8 ignore stop */
//@ts-ignore
import serviceKeyCJS from '../commonjs/service-key.js'
export const { serviceKey } = serviceKeyCJS as { serviceKey: string }

0 comments on commit 556e520

Please sign in to comment.