Skip to content

Commit

Permalink
docs: rephrase the readme
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Mar 18, 2024
1 parent bcaf74e commit 5dd1c3f
Show file tree
Hide file tree
Showing 3 changed files with 199 additions and 160 deletions.
52 changes: 44 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,59 @@
<h1 align="center">jest-fixed-jsdom</h1>
<p align="center">This library helps re-attach missing NodeJS globals definitions in JSDOM that Jest strips out</p>
<p align="center">A superset of the JSDOM environment for Jest that respects Node.js globals.</p>

## Motivation

Jest strips out a number of NodeJS globals that are used in tests and libraries involving JSDOM, such as structuredClone, ReadableStream, and so on. This library patches these globals back in - there is no polyfilling or mocking involved, it simply re-attaches the missing globals to the JSDOM environment. If you've ever come across errors such as `ReferenceError: ReadableStream is not defined` or `ReferenceError: structuredClone is not defined`, this library is for you. If you were previously using (undici)[https://www.npmjs.com/package/undici] purely to solve this, you will no longer need it.
When you use Jest with JSDOM you are getting a broken test environment. Some Node.js globals cease to exist (e.g. `Request`, `Response`, `TextEncoder`, `TextDecoder`, `ReadableStream`<sup><a href="https://github.com/mswjs/msw/issues/1916">1</a></sup>), while others stop behaving correctly (e.g. `Event`, `MessageEvent`<sup><a href="https://github.com/nodejs/undici/issues/2663">2</a></sup>, `structuredClone()`<sup><a href="https://github.com/mswjs/msw/issues/1931">3</a></sup>). That is caused by `jest-environment-jsdom` and JSDOM relying on polyfills to implement standard APIs that have been available globally both in the browser and in Node.js for years.

## Installation
Here's a piece of valid JavaScript that works in both the browser and Node.js but fails in Jest/JSDOM:

`npm install jest-fixed-jsdom -D`
```js
new TextEncoder().encode('hello')
```

```
ReferenceError: TextEncoder is not defined
```

**We strongly believe that a valid JavaScript code must compile regardless of what test environment you are using**. In fact, having a proper test environment is crucial to get any kind of value from your tests. Jest/JSDOM take that already working environment away from you.

We've built this project aims to fix that problem, restoring the global APIs that are present in both environments, providing better interoperability, stability, and consistent runtime behavior.

## Changes

## Configuring your jest environment to use jest-fixed-jsdom
This project "fixes" the following global APIs, overriding whichever polyfills they have with respective Node.js globals:

You will need to add/modify two properties in your jest configuration to use jest-fixed-jsdom.
- `EventTarget`
- `Event`
- `MessageEvent`
- `fetch()`
- `Blob`
- `FormData`
- `Headers`
- `Request`
- `Response`
- `ReadableStream`
- `TextEncoder`
- `TextDecoder`
- `structuredClone()`

## Getting started

### Install

```sh
npm i jest-fixed-jsdom --save-dev
```

### Configure Jest

In your `jest.config.js`, set the `testEnvironment` option to `jest-fixed-jsdom`:

```json
// jest.config.js
{
"testEnvironment": "jest-fixed-jsdom"
}
```

Setting `testEnvironment` to `jest-fixed-jsdom` will tell Jest to use jest-fixed-jsdom as the test environment. Setting `customExportConditions` to an empty array will stop JSDOM from using the browser environment to load exports.

> You can use any other `testEnvironmentOptions` you need. Those will be forwarded to the underlying `jest-environment-jsdom`.
304 changes: 153 additions & 151 deletions index.test.js
Original file line number Diff line number Diff line change
@@ -1,151 +1,153 @@
test('exposes "Blob"', async () => {
expect(globalThis).toHaveProperty('Blob')
expect(() => new Blob()).not.toThrow()
await expect(new Blob(['hello']).text()).resolves.toBe('hello')
})

test('exposes "TextEncoder"', () => {
expect(globalThis).toHaveProperty('TextEncoder')
expect(() => new TextEncoder()).not.toThrow()
expect(Buffer.from(new TextEncoder().encode('hello'))).toEqual(
Buffer.from(new Uint8Array([104, 101, 108, 108, 111])),
)
})

test('exposes "TextDecoder"', () => {
expect(globalThis).toHaveProperty('TextDecoder')
expect(() => new TextDecoder()).not.toThrow()
expect(
new TextDecoder().decode(new Uint8Array([104, 101, 108, 108, 111])),
).toBe('hello')
})

test('exposes "ReadableStream"', () => {
expect(globalThis).toHaveProperty('ReadableStream')
expect(() => new ReadableStream()).not.toThrow()
})

test('exposes "Headers"', () => {
expect(globalThis).toHaveProperty('Headers')
expect(() => new Headers()).not.toThrow()
expect(new Headers([['a', 'b']]).get('a')).toBe('b')
})

test('exposes "FormData"', () => {
expect(globalThis).toHaveProperty('FormData')
expect(() => new FormData()).not.toThrow()

const data = new FormData()
data.set('a', 'b')
expect(data.get('a')).toBe('b')
})

test('exposes "Request"', async () => {
expect(globalThis).toHaveProperty('Request')
expect(() => new Request('https://example.com')).not.toThrow()

const request = new Request('https://example.com', {
method: 'POST',
body: 'hello world',
})
expect(await request.text()).toBe('hello world')
})

test('exposes "Response"', async () => {
expect(globalThis).toHaveProperty('Response')
expect(() => new Response('hello')).not.toThrow()

const response = new Response('hello')
expect(await response.text()).toBe('hello')
})

test('exposes "structuredClone"', async () => {
expect(globalThis).toHaveProperty('structuredClone')
expect(() => structuredClone('hello')).not.toThrow()
expect(structuredClone('hello')).toBe('hello')

const stream = new ReadableStream({
start(controller) {
controller.enqueue('hello')
controller.close()
},
})
/**
* @note Jest/JSDOM failes cloning ReadableStream because they use
* "core-js" to polyfill "structuredClone()" and it doesn't support it.
* @see https://github.com/mswjs/msw/issues/1929#issuecomment-1908535966
*/
const clone = structuredClone(stream, { transfer: [stream] })
expect(clone).toBeInstanceOf(ReadableStream)

const chunks = []
const reader = clone.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
}
expect(chunks).toEqual(['hello'])
})

test('exposes "EventTarget"', () => {
expect(globalThis).toHaveProperty('EventTarget')
expect(() => new EventTarget()).not.toThrow()

const target = new EventTarget()
const symbols = Object.getOwnPropertySymbols(target).map(
(symbol) => symbol.description,
)

// EventTarget must not be implemented by JSDOM.
expect(symbols).not.toContain('impl')

// In Node.js, EventTarget keeps events behind the kEvents symbol.
expect(symbols).toContain('kEvents')
})

test('exposes "Event"', () => {
expect(globalThis).toHaveProperty('Event')
expect(() => new Event('click')).not.toThrow()

const event = new Event('click')
const symbols = Object.getOwnPropertySymbols(event).map(
(symbol) => symbol.description,
)

// The "impl" symbol is added by JSDOM.
expect(symbols).not.toContain('impl')
// Node.js expects events to have the "type" symbol.
expect(symbols).toContain('type')

/**
* Perform a basic "isEvent()" check that Node.js has.
* @see https://github.com/nodejs/node/blob/3a456c6db802b5b25594d3a9d235d4989e9f7829/lib/internal/event_target.js#L96
*/
expect(event[symbols.find((description) => description === 'type')]).toBe(
'click',
)
})

test('exposes "MessageEvent"', () => {
expect(globalThis).toHaveProperty('MessageEvent')
expect(() => new MessageEvent('click')).not.toThrow()

const event = new MessageEvent('message')
const symbols = Object.getOwnPropertySymbols(event).map(
(symbol) => symbol.description,
)

// The "impl" symbol is added by JSDOM.
expect(symbols).not.toContain('impl')
// Node.js expects events to have the "type" symbol.
expect(symbols).toContain('type')

/**
* Perform a basic "isEvent()" check that Node.js has.
* @see https://github.com/nodejs/node/blob/3a456c6db802b5b25594d3a9d235d4989e9f7829/lib/internal/event_target.js#L96
*/
expect(event[symbols.find((description) => description === 'type')]).toBe(
'message',
)
})
new TextEncoder().encode('hello')

// test('exposes "Blob"', async () => {
// expect(globalThis).toHaveProperty('Blob')
// expect(() => new Blob()).not.toThrow()
// await expect(new Blob(['hello']).text()).resolves.toBe('hello')
// })

// test('exposes "TextEncoder"', () => {
// expect(globalThis).toHaveProperty('TextEncoder')
// expect(() => new TextEncoder()).not.toThrow()
// expect(Buffer.from(new TextEncoder().encode('hello'))).toEqual(
// Buffer.from(new Uint8Array([104, 101, 108, 108, 111])),
// )
// })

// test('exposes "TextDecoder"', () => {
// expect(globalThis).toHaveProperty('TextDecoder')
// expect(() => new TextDecoder()).not.toThrow()
// expect(
// new TextDecoder().decode(new Uint8Array([104, 101, 108, 108, 111])),
// ).toBe('hello')
// })

// test('exposes "ReadableStream"', () => {
// expect(globalThis).toHaveProperty('ReadableStream')
// expect(() => new ReadableStream()).not.toThrow()
// })

// test('exposes "Headers"', () => {
// expect(globalThis).toHaveProperty('Headers')
// expect(() => new Headers()).not.toThrow()
// expect(new Headers([['a', 'b']]).get('a')).toBe('b')
// })

// test('exposes "FormData"', () => {
// expect(globalThis).toHaveProperty('FormData')
// expect(() => new FormData()).not.toThrow()

// const data = new FormData()
// data.set('a', 'b')
// expect(data.get('a')).toBe('b')
// })

// test('exposes "Request"', async () => {
// expect(globalThis).toHaveProperty('Request')
// expect(() => new Request('https://example.com')).not.toThrow()

// const request = new Request('https://example.com', {
// method: 'POST',
// body: 'hello world',
// })
// expect(await request.text()).toBe('hello world')
// })

// test('exposes "Response"', async () => {
// expect(globalThis).toHaveProperty('Response')
// expect(() => new Response('hello')).not.toThrow()

// const response = new Response('hello')
// expect(await response.text()).toBe('hello')
// })

// test('exposes "structuredClone"', async () => {
// expect(globalThis).toHaveProperty('structuredClone')
// expect(() => structuredClone('hello')).not.toThrow()
// expect(structuredClone('hello')).toBe('hello')

// const stream = new ReadableStream({
// start(controller) {
// controller.enqueue('hello')
// controller.close()
// },
// })
// /**
// * @note Jest/JSDOM failes cloning ReadableStream because they use
// * "core-js" to polyfill "structuredClone()" and it doesn't support it.
// * @see https://github.com/mswjs/msw/issues/1929#issuecomment-1908535966
// */
// const clone = structuredClone(stream, { transfer: [stream] })
// expect(clone).toBeInstanceOf(ReadableStream)

// const chunks = []
// const reader = clone.getReader()
// while (true) {
// const { done, value } = await reader.read()
// if (done) break
// chunks.push(value)
// }
// expect(chunks).toEqual(['hello'])
// })

// test('exposes "EventTarget"', () => {
// expect(globalThis).toHaveProperty('EventTarget')
// expect(() => new EventTarget()).not.toThrow()

// const target = new EventTarget()
// const symbols = Object.getOwnPropertySymbols(target).map(
// (symbol) => symbol.description,
// )

// // EventTarget must not be implemented by JSDOM.
// expect(symbols).not.toContain('impl')

// // In Node.js, EventTarget keeps events behind the kEvents symbol.
// expect(symbols).toContain('kEvents')
// })

// test('exposes "Event"', () => {
// expect(globalThis).toHaveProperty('Event')
// expect(() => new Event('click')).not.toThrow()

// const event = new Event('click')
// const symbols = Object.getOwnPropertySymbols(event).map(
// (symbol) => symbol.description,
// )

// // The "impl" symbol is added by JSDOM.
// expect(symbols).not.toContain('impl')
// // Node.js expects events to have the "type" symbol.
// expect(symbols).toContain('type')

// /**
// * Perform a basic "isEvent()" check that Node.js has.
// * @see https://github.com/nodejs/node/blob/3a456c6db802b5b25594d3a9d235d4989e9f7829/lib/internal/event_target.js#L96
// */
// expect(event[symbols.find((description) => description === 'type')]).toBe(
// 'click',
// )
// })

// test('exposes "MessageEvent"', () => {
// expect(globalThis).toHaveProperty('MessageEvent')
// expect(() => new MessageEvent('click')).not.toThrow()

// const event = new MessageEvent('message')
// const symbols = Object.getOwnPropertySymbols(event).map(
// (symbol) => symbol.description,
// )

// // The "impl" symbol is added by JSDOM.
// expect(symbols).not.toContain('impl')
// // Node.js expects events to have the "type" symbol.
// expect(symbols).toContain('type')

// /**
// * Perform a basic "isEvent()" check that Node.js has.
// * @see https://github.com/nodejs/node/blob/3a456c6db802b5b25594d3a9d235d4989e9f7829/lib/internal/event_target.js#L96
// */
// expect(event[symbols.find((description) => description === 'type')]).toBe(
// 'message',
// )
// })
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
module.exports = {
testEnvironment: '<rootDir>/index.js',
// testEnvironment: '<rootDir>/index.js',
testEnvironment: 'jsdom',
}

0 comments on commit 5dd1c3f

Please sign in to comment.