dnt icon indicating copy to clipboard operation
dnt copied to clipboard

How to set globals for tests only?

Open tom-sherman opened this issue 3 years ago • 2 comments

I want to publish the library to npm so that it assumes some globals exist eg. Headers, Response, ReadableStream.

I don't want these globals to be shimmed in any way, I instead want them set onto globalThis for the purposes of running tests on node only. I don't want to ship these shimmed to npm.

I've tried setting shims as follows:

shims: {
  deno: {
    test: "dev",
  },
  customDev: [{
    package: {
      name: "undici",
      version: "^5.2.0",
    },
    globalNames: ["Headers", "FormData", "Response", "Request"],
  }],
},

However this doesn't work, the globals don't appear to be set. See https://github.com/tom-sherman/response-multipart/tree/2b3ca792ec6896910d0b44364e8e5bab73553d78 for reproduction

tom-sherman avatar Jun 24 '22 23:06 tom-sherman

For now I'm doing two builds: one for testing purposes that includes all the relevant shims in dev and non-dev code, and another that includes no shims intended for publishing to npm.

See https://github.com/tom-sherman/response-multipart/commit/208c4f67e55d31ecae7d6fb1dd192db3b484e0b1

This isn't ideal obviously, I'd prefer to only have to do a single build.

tom-sherman avatar Jun 25 '22 09:06 tom-sherman

Bumping this as it's still an issue in 2023. I want shims: { crypto: true } to only be set when test_runner.js is run to test CJS and ESM output. Otherwise when my code attempts to leverage globalThis.crypto after an attempt to require("node:crypto") fails, the code (intentionally) throws an error and then the test fails.

This code otherwise works fine when I execute it in Node and Deno, it's only during tests when globalThis.crypto is undefined that it fails.

The only way to achieve right now is still to set up two different builds like @tom-sherman advises in the comment above.

MasterKale avatar Aug 18 '23 20:08 MasterKale