https://github.com/hrsh7th/xhr-snapshot
https://github.com/hrsh7th/xhr-snapshot
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/hrsh7th/xhr-snapshot
- Owner: hrsh7th
- Created: 2022-02-04T12:02:24.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-02-04T12:54:30.000Z (over 3 years ago)
- Last Synced: 2025-02-22T12:42:26.041Z (8 months ago)
- Language: TypeScript
- Size: 74.2 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# xhr-snapshot
Create snapshot of XMLHttpRequest for testing.
### Usage
1. Setup [jest](https://jestjs.io)
```tsx
# jest.config.jsmodule.exports = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
url: '%YOUR SISE ORIGIN%'
},
setupFilesAfterEnv: ['/jest.setup.js']
}
``````tsx
# jest.setup.jsimport 'whatwg-fetch';
import { resolve } from 'path';
import { configure } from 'xhr-snapshot';configure({
snapshotDir: resolve(__dirname, '__xhr_snapshots__'),
updateSnapshot: process.argv.includes('--update-snapshot'),
})
```2. Run your jest tests with actual fetch requests.
```tsx
import { normalize } from '../src/normalize';describe('awesome tests', () => {
it('should create the normalized state', () => {
const response = await fetch('...').then(res => res.json());
expect(normalize(response)).toMatchSnapshot();
});});
```### How does it works?
In the current jsdom environment, all ajax requests is done via `XMLHttpRequest`.
So we can hijack it via replacing `window.XMLHttpRequest`.
The `XMLHttpRequest` hijacking is done via `nise` module provided by the SinonJS team.
The `fetch` isn't defined in current Node.js and jsdom environment so your `fetch` request will be passed for `XMLHttpRequest` via `whatwg-fetch`.