Skip to content

fix: TextEncoder not defined in Node.js test environments - #416

Open
thiagobarbosa wants to merge 1 commit into
spotify:mainfrom
thiagobarbosa:fix/define-text-coder-in-node-test
Open

fix: TextEncoder not defined in Node.js test environments#416
thiagobarbosa wants to merge 1 commit into
spotify:mainfrom
thiagobarbosa:fix/define-text-coder-in-node-test

Conversation

@thiagobarbosa

Copy link
Copy Markdown

Fix #268

Problem

Confidence.showLoggerLink() picks its base64 encoder by sniffing for window:

const base64 = typeof window !== 'undefined' ? utf8ToBase64(jsonString) : Buffer.from(jsonString).toString('base64');

utf8ToBase64() (packages/sdk/src/utils.ts) calls new TextEncoder(). The check assumes that "window exists" implies "a full browser environment exists", which does not hold in simulated DOM test environments (e.g. Jest with testEnvironment: 'jsdom', older jsdom versions, or any setup that defines window without polyfilling TextEncoder).

In those environments the debug logger link throws ReferenceError: TextEncoder is not defined, which surfaces during flag evaluation and breaks consumers' test suites even though nothing about the flag evaluation itself is wrong.

Change

Widen the guard so it feature-detects TextEncoder instead of inferring it from window, falling back to Buffer when the encoder is unavailable:

const base64 =
  typeof window !== 'undefined' && typeof TextEncoder !== 'undefined'
    ? utf8ToBase64(jsonString)
    : Buffer.from(jsonString).toString('base64');

Real browsers are unaffected — they have both window and TextEncoder, so they keep taking the utf8ToBase64() path. Only the broken environment changes behaviour, and there it degrades to the Node encoder rather than throwing.

Tests

Added a regression test in packages/sdk/src/Confidence.test.ts that:

  • defines global.window while deleting global.TextEncoder, simulating a DOM-ish environment without the encoder,
  • evaluates a flag and asserts that it does not throw,
  • asserts that the "Resolve tester" logger link is still emitted (i.e. the fallback produces output rather than silently skipping),
  • restores the original window / TextEncoder globals in a finally block so surrounding tests are unaffected.

npx jest packages/sdk/src/Confidence.test.ts — 29 passed, including the new case.

Files changed

File Change
packages/sdk/src/Confidence.ts Feature-detect TextEncoder before using utf8ToBase64()
packages/sdk/src/Confidence.test.ts Regression test for the missing-TextEncoder environment

Resolves spotify#268
spotify#268

Generated by issue-coder. Review before pushing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TextEncoder not defined in Node.js test environments

1 participant