Skip to content

Commit 0429a1f

Browse files
committed
Manual review
1 parent 38baf09 commit 0429a1f

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+4232
-517
lines changed

README.md

Lines changed: 229 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@ A set of tools for emulating browser behavior in jsdom environment
1919
[matchMedia](#mock-viewport)
2020
[Intersection Observer](#mock-intersectionobserver)
2121
[Resize Observer](#mock-resizeobserver)
22-
[Web Animations API](#mock-web-animations-api)
23-
[CSS Typed OM](#mock-css-typed-om)
22+
[Web Animations API](#mock-web-animations-api) (includes ScrollTimeline and ViewTimeline)
23+
[CSS Typed OM](#mock-css-typed-om)
24+
[Scroll Methods](#scroll-methods) (scrollTo, scrollBy, scrollIntoView)
2425

2526
## Installation
2627

@@ -42,11 +43,45 @@ To avoid having to wrap everything in `act` calls, you can pass `act` to `config
4243
import { configMocks } from 'jsdom-testing-mocks';
4344
import { act } from '...';
4445

45-
configMocks({ act });
46+
configMocks({
47+
act,
48+
// Optional: Configure smooth scrolling behavior
49+
smoothScrolling: {
50+
enabled: false, // Enable/disable smooth scrolling (default: false for fast tests)
51+
duration: 300, // Animation duration in ms (default: 300)
52+
steps: 10 // Number of animation frames (default: 10)
53+
}
54+
});
4655
```
4756

4857
It can be done in a setup file, or in a test file, before rendering the component.
4958

59+
### Configuration Options
60+
61+
You can configure various aspects of the mocks using `configMocks()`:
62+
63+
```javascript
64+
import { configMocks } from 'jsdom-testing-mocks';
65+
66+
configMocks({
67+
// Test lifecycle hooks (required for some testing frameworks)
68+
beforeAll,
69+
afterAll,
70+
beforeEach,
71+
afterEach,
72+
73+
// React integration - avoids wrapping everything in act() calls
74+
act,
75+
76+
// Scroll behavior configuration
77+
smoothScrolling: {
78+
enabled: false, // Disable smooth scrolling for faster tests (default: false)
79+
duration: 300, // Animation duration when enabled (default: 300)
80+
steps: 10 // Animation frame count when enabled (default: 10)
81+
}
82+
});
83+
```
84+
5085
### With `vitest`
5186

5287
Some mocks require lifecycle hooks to be defined on the global object. To make it work with vitest, you need to [enable globals in your config](https://vitest.dev/config/#globals). If you don't want to do that you can pass it manually using `configMocks`.
@@ -345,6 +380,44 @@ _Warning: **experimental**, bug reports, tests and feedback are greatly apprecia
345380

346381
Mocks WAAPI functionality using `requestAnimationFrame`. With one important limitation — there are no style interpolations. Each frame applies the closest keyframe from list of passed keyframes or a generated "initial keyframe" if only one keyframe is passed (initial keyframe removes/restores all the properties set by the one keyframe passed). As the implementation is based on the [official spec](https://www.w3.org/TR/web-animations-1/) it should support the majority of cases, but the test suite is far from complete, so _here be dragons_
347382

383+
### ScrollTimeline and ViewTimeline Support
384+
385+
The mock includes complete implementations of **ScrollTimeline** and **ViewTimeline** for scroll-driven animations:
386+
387+
- **ScrollTimeline** - Creates animations driven by scroll position of a container
388+
- **ViewTimeline** - Creates animations driven by an element's visibility in its scroll container
389+
390+
```javascript
391+
import { mockAnimationsApi } from 'jsdom-testing-mocks';
392+
393+
mockAnimationsApi();
394+
395+
// ScrollTimeline example
396+
const container = document.querySelector('.scroll-container');
397+
const scrollTimeline = new ScrollTimeline({
398+
source: container,
399+
axis: 'block',
400+
scrollOffsets: ['0%', '100%']
401+
});
402+
403+
// ViewTimeline example
404+
const subject = document.querySelector('.animated-element');
405+
const viewTimeline = new ViewTimeline({
406+
subject: subject,
407+
axis: 'block',
408+
inset: ['0px', '0px']
409+
});
410+
411+
// Use with Web Animations API
412+
subject.animate([
413+
{ opacity: 0, transform: 'scale(0.8)' },
414+
{ opacity: 1, transform: 'scale(1)' }
415+
], {
416+
timeline: viewTimeline,
417+
duration: 1000
418+
});
419+
```
420+
348421
Example, using `React Testing Library`:
349422

350423
```jsx
@@ -442,6 +515,159 @@ it('enforces type safety', () => {
442515

443516
Supports all CSS units (length, angle, time, frequency, resolution, flex, percentage), mathematical operations, and enforces type compatibility rules as defined in the [W3C specification](https://www.w3.org/TR/css-typed-om-1/).
444517

518+
## Scroll Methods
519+
520+
Provides native scroll method implementations (`scrollTo`, `scrollBy`, `scrollIntoView`) that properly update scroll properties and trigger scroll events. Essential for testing scroll-driven animations and scroll behavior.
521+
522+
**Supports smooth scrolling behavior** - When `behavior: 'smooth'` is specified, the mock can animate the scroll over multiple frames using configurable settings, or treat it as immediate for faster tests.
523+
524+
### Configuration Options
525+
526+
```javascript
527+
import { mockScrollMethods, configMocks } from 'jsdom-testing-mocks';
528+
529+
// Configure scroll behavior globally (call before using mockScrollMethods)
530+
configMocks({
531+
smoothScrolling: {
532+
enabled: false, // Enable/disable smooth scrolling animation (default: false)
533+
duration: 300, // Animation duration in ms (default: 300)
534+
steps: 10 // Number of animation frames (default: 10)
535+
}
536+
});
537+
```
538+
539+
**Configuration Options:**
540+
- `enabled: false` - (Default) Treats all scrolling as immediate, ignoring `behavior: 'smooth'` (fastest for tests)
541+
- `enabled: true` - Respects `behavior: 'smooth'` and animates over multiple frames
542+
- `duration` - How long the smooth scroll animation takes
543+
- `steps` - How many intermediate positions to animate through
544+
545+
### Usage Examples
546+
547+
```javascript
548+
// Mock scroll methods for an element
549+
const element = document.createElement('div');
550+
const restore = mockScrollMethods(element);
551+
552+
// Immediate scrolling (default behavior)
553+
element.scrollTo({ top: 100 });
554+
element.scrollBy(0, 50);
555+
556+
// Smooth scrolling behavior depends on configuration:
557+
// - If enabled: false (default) -> immediate (ignores 'smooth')
558+
// - If enabled: true -> animates over multiple frames
559+
element.scrollTo({ top: 200, behavior: 'smooth' });
560+
element.scrollBy({ top: 50, behavior: 'smooth' });
561+
element.scrollIntoView({ block: 'center', behavior: 'smooth' });
562+
563+
// All scroll methods work with both element and window
564+
window.scrollTo({ top: 300, behavior: 'smooth' });
565+
566+
// Scroll events are dispatched and ScrollTimelines/ViewTimelines are updated
567+
const scrollTimeline = new ScrollTimeline({ source: element });
568+
569+
// Cleanup when done
570+
restore();
571+
```
572+
573+
### Common Configurations
574+
575+
```javascript
576+
// Default test configuration - all scrolling is immediate (default behavior)
577+
// No configuration needed, this is the default:
578+
// configMocks({ smoothScrolling: { enabled: false } });
579+
580+
// Enable smooth scrolling for animation testing
581+
configMocks({
582+
smoothScrolling: { enabled: true } // Use default duration: 300, steps: 10
583+
});
584+
585+
// Custom smooth scrolling - slow, high-fidelity animations
586+
configMocks({
587+
smoothScrolling: {
588+
enabled: true,
589+
duration: 1000, // 1 second animation
590+
steps: 60 // 60 animation frames
591+
}
592+
});
593+
```
594+
595+
### Setup File Example
596+
597+
Create a test setup file to configure mocks globally:
598+
599+
```javascript
600+
// test-setup.js or setupTests.js
601+
import { configMocks } from 'jsdom-testing-mocks';
602+
import { act } from '@testing-library/react'; // or your testing framework
603+
604+
configMocks({
605+
act,
606+
smoothScrolling: {
607+
enabled: false // Fast tests - disable smooth scrolling
608+
}
609+
});
610+
```
611+
612+
Then import this in your test configuration (Jest, Vitest, etc.).
613+
614+
615+
## Testing Helpers
616+
617+
Additional utilities for mocking element properties in tests:
618+
619+
### Element Dimensions and Positioning
620+
621+
**`mockElementBoundingClientRect(element, rect)`** - Mock `getBoundingClientRect()` return values for positioning and layout
622+
623+
**`mockDOMRect()`** - Mock `DOMRect` and `DOMRectReadOnly` constructors
624+
625+
### Element Size Properties
626+
627+
**`mockElementClientProperties(element, props)`** - Mock visible area dimensions (`clientHeight`, `clientWidth`, `clientTop`, `clientLeft`)
628+
629+
**`mockElementScrollProperties(element, props)`** - Mock scroll position and content dimensions (`scrollTop`, `scrollLeft`, `scrollHeight`, `scrollWidth`)
630+
631+
### Scroll Testing
632+
633+
**`mockScrollMethods(element)`** - Mock native scroll methods (`scrollTo`, `scrollBy`, `scrollIntoView`) for proper testing
634+
635+
```javascript
636+
import {
637+
mockElementScrollProperties,
638+
mockElementClientProperties,
639+
mockScrollMethods
640+
} from 'jsdom-testing-mocks';
641+
642+
const element = document.createElement('div');
643+
644+
// Mock element dimensions
645+
mockElementClientProperties(element, {
646+
clientHeight: 200,
647+
clientWidth: 300
648+
});
649+
650+
// Mock scroll properties
651+
mockElementScrollProperties(element, {
652+
scrollTop: 100,
653+
scrollHeight: 1000,
654+
scrollWidth: 500
655+
});
656+
657+
// Enable native scroll methods
658+
const restore = mockScrollMethods(element);
659+
660+
// Use native scroll methods - they now work properly and trigger events
661+
element.scrollTo({ top: 250, behavior: 'smooth' });
662+
663+
// Test scroll progress
664+
const progress = element.scrollTop / (element.scrollHeight - element.clientHeight);
665+
expect(progress).toBe(0.3125); // 31.25%
666+
667+
// Cleanup when done
668+
restore();
669+
```
670+
445671
## Current issues
446672

447673
- Needs more tests

examples/README.md

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +0,0 @@
1-
# Getting Started with Create React App
2-
3-
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4-
5-
## Available Scripts
6-
7-
In the project directory, you can run:
8-
9-
### `npm start`
10-
11-
Runs the app in the development mode.\
12-
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13-
14-
The page will reload if you make edits.\
15-
You will also see any lint errors in the console.
16-
17-
### `npm test`
18-
19-
Launches the test runner in the interactive watch mode.\
20-
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21-
22-
### `npm run build`
23-
24-
Builds the app for production to the `build` folder.\
25-
It correctly bundles React in production mode and optimizes the build for the best performance.
26-
27-
The build is minified and the filenames include the hashes.\
28-
Your app is ready to be deployed!
29-
30-
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31-
32-
### `npm run eject`
33-
34-
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35-
36-
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37-
38-
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39-
40-
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41-
42-
## Learn More
43-
44-
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45-
46-
To learn React, check out the [React documentation](https://reactjs.org/).

examples/index.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@
88
<body>
99
<noscript>You need to enable JavaScript to run this app.</noscript>
1010
<div id="root"></div>
11+
<script type="module" src="/src/index.tsx"></script>
1112
</body>
1213
</html>

examples/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
"start": "vite",
2020
"build": "vite build",
2121
"preview": "vite preview",
22-
"test:jest": "jest --config ./swcjest.config.js",
23-
"test:swc": "jest --config ./swcjest.config.js",
22+
"test:jest": "jest --config ./swcjest.config.ts",
23+
"test:swc": "jest --config ./swcjest.config.ts",
2424
"test:vi": "vitest --config ./vitest.config.ts run",
2525
"test:all": "npm run test:jest && npm run test:vi && npm run test:swc",
2626
"lint": "eslint src --ext .ts,.tsx,.js,.jsx",

examples/src/App.tsx

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,43 @@ import DeprecatedCustomUseMedia from './components/viewport/deprecated-use-media
1010
import { Layout } from './components/animations/Layout';
1111
import AnimationsInView from './components/animations/examples/inview/InView';
1212
import AnimationsAnimatePresence from './components/animations/examples/animate-presence/AnimatePresence';
13+
import { ScrollTimelineExample } from './components/animations/examples/scroll-timeline/ScrollTimeline';
14+
import { ViewTimelineExample } from './components/animations/examples/view-timeline/ViewTimeline';
1315
import AnimationsIndex from './components/animations';
1416

1517
function Index() {
16-
return <></>;
18+
return (
19+
<div style={{ padding: '2rem', maxWidth: '800px', margin: '0 auto' }}>
20+
<h1>jsdom-testing-mocks Examples</h1>
21+
<p>
22+
This app demonstrates real-world behavior of browser APIs alongside their mocked equivalents.
23+
Use the navigation above to explore different examples.
24+
</p>
25+
26+
<h2>Available Examples</h2>
27+
<div style={{ display: 'grid', gap: '1rem', marginTop: '1rem' }}>
28+
<div style={{ border: '1px solid #ccc', padding: '1rem', borderRadius: '4px' }}>
29+
<h3>Intersection Observer</h3>
30+
<p>Demonstrates element visibility detection and scroll-based triggers.</p>
31+
</div>
32+
33+
<div style={{ border: '1px solid #ccc', padding: '1rem', borderRadius: '4px' }}>
34+
<h3>Resize Observer</h3>
35+
<p>Shows element size change detection with practical use cases.</p>
36+
</div>
37+
38+
<div style={{ border: '1px solid #ccc', padding: '1rem', borderRadius: '4px' }}>
39+
<h3>Viewport / Media Queries</h3>
40+
<p>Responsive design patterns and viewport-based behavior.</p>
41+
</div>
42+
43+
<div style={{ border: '1px solid #ccc', padding: '1rem', borderRadius: '4px' }}>
44+
<h3>Web Animations API</h3>
45+
<p>Advanced animation examples including scroll-driven animations.</p>
46+
</div>
47+
</div>
48+
</div>
49+
);
1750
}
1851

1952
function App() {
@@ -38,6 +71,8 @@ function App() {
3871
path="animate-presence"
3972
element={<AnimationsAnimatePresence />}
4073
/>
74+
<Route path="scroll-timeline" element={<ScrollTimelineExample />} />
75+
<Route path="view-timeline" element={<ViewTimelineExample />} />
4176
<Route index element={<AnimationsIndex />} />
4277
</Route>
4378
<Route path="/" element={<Index />} />

examples/src/components/animations/Nav.tsx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ const Nav = () => {
1010
<li>
1111
<a href="/animations/animate-presence">AnimatePresence</a>
1212
</li>
13+
<li>
14+
<a href="/animations/scroll-timeline">ScrollTimeline API</a>
15+
</li>
16+
<li>
17+
<a href="/animations/view-timeline">ViewTimeline API</a>
18+
</li>
1319
</ul>
1420
</nav>
1521
);

0 commit comments

Comments
 (0)