Skip to content

TextEncoder not defined in Node.js test environments #268

@nicklasl

Description

@nicklasl

Problem:

The SDK's base64 encoding logic incorrectly assumes TextEncoder availability based solely on the typeof window !== 'undefined' check. This leads to a ReferenceError in certain Node.js test environments (e.g., Jest with jsdom).

Affected Line:
The issue stems from the following line in packages/sdk/src/utils.ts#L40:

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

##Error Observed:

When running tests in environments like Jest with jsdom, the following error is thrown:

ReferenceError: TextEncoder is not defined

Root Cause:

jsdom environments define the window object to simulate a browser but don't always include all Web APIs, such as TextEncoder, by default. The typeof window !== 'undefined' condition evaluates to true, causing the code to use utf8ToBase64 (which relies on TextEncoder). Since TextEncoder is missing, the ReferenceError occurs.

Impact:

This prevents successful execution of tests in Node.js environments that rely on jsdom without explicit polyfills for TextEncoder, hindering development and CI processes.

Suggested Solution:
Consider a more precise check for the availability of TextEncoder directly:

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

Alternatively, the utf8ToBase64 function itself could be made more resilient by including an internal fallback or polyfill if TextEncoder is not available, even if window is present. This would reduce the burden on SDK consumers to add specific polyfills to their test setups.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions