1
1
import * as React from "react" ;
2
- import { createMemoryRouter , RouterProvider , Outlet } from "react-router-dom" ;
2
+ import {
3
+ createMemoryRouter ,
4
+ RouterProvider ,
5
+ Outlet ,
6
+ redirect ,
7
+ } from "react-router-dom" ;
3
8
import { render , screen } from "@testing-library/react" ;
4
9
5
10
import { RemixContext , Scripts } from "../components" ;
@@ -11,7 +16,13 @@ import "@testing-library/jest-dom/extend-expect";
11
16
describe ( "<ScrollRestoration />" , ( ) => {
12
17
let scrollTo = window . scrollTo ;
13
18
beforeAll ( ( ) => {
14
- window . scrollTo = ( ) => { } ;
19
+ window . scrollTo = ( options ) => {
20
+ window . scrollY = options . left ;
21
+ } ;
22
+ } ) ;
23
+
24
+ afterEach ( ( ) => {
25
+ jest . resetAllMocks ( ) ;
15
26
} ) ;
16
27
afterAll ( ( ) => {
17
28
window . scrollTo = scrollTo ;
@@ -89,5 +100,62 @@ describe("<ScrollRestoration />", () => {
89
100
expect ( script ) . toHaveAttribute ( "crossorigin" , "anonymous" ) ;
90
101
} ) ;
91
102
92
- it . todo ( "should restore scroll position" ) ;
103
+ it ( "should restore scroll position" , ( ) => {
104
+ let scrollToMock = jest . spyOn ( window , "scrollTo" ) ;
105
+ let router = createMemoryRouter ( [
106
+ {
107
+ id : "root" ,
108
+ path : "/" ,
109
+ element : (
110
+ < >
111
+ < Outlet />
112
+ < ScrollRestoration />
113
+ < Scripts />
114
+ </ >
115
+ ) ,
116
+ } ,
117
+ ] ) ;
118
+ router . state . restoreScrollPosition = 20 ;
119
+ render (
120
+ < RemixContext . Provider value = { context } >
121
+ < RouterProvider router = { router } />
122
+ </ RemixContext . Provider >
123
+ ) ;
124
+
125
+ expect ( scrollToMock ) . toHaveBeenCalledWith ( 0 , 20 ) ;
126
+ } ) ;
127
+
128
+ it ( "should restore scroll position on navigation" , ( ) => {
129
+ let scrollToMock = jest . spyOn ( window , "scrollTo" ) ;
130
+ let router = createMemoryRouter ( [
131
+ {
132
+ id : "root" ,
133
+ path : "/" ,
134
+ element : (
135
+ < >
136
+ < Outlet />
137
+ < ScrollRestoration />
138
+ < Scripts />
139
+ </ >
140
+ ) ,
141
+ } ,
142
+ ] ) ;
143
+ render (
144
+ < RemixContext . Provider value = { context } >
145
+ < RouterProvider router = { router } />
146
+ </ RemixContext . Provider >
147
+ ) ;
148
+ // Always called when using <ScrollRestoration />
149
+ expect ( scrollToMock ) . toHaveBeenCalledWith ( 0 , 0 ) ;
150
+ // Mock user scroll
151
+ window . scrollTo ( 0 , 20 ) ;
152
+ // Mock navigation
153
+ redirect ( "/otherplace" ) ;
154
+ // Mock return to original page where navigation had happened
155
+ expect ( scrollToMock ) . toHaveBeenCalledWith ( 0 , 0 ) ;
156
+ // Mock return to original page where navigation had happened
157
+ redirect ( "/" ) ;
158
+ // Ensure that scroll position is restored
159
+ expect ( scrollToMock ) . toHaveBeenCalledWith ( 0 , 20 ) ;
160
+ } ) ;
93
161
} ) ;
0 commit comments