]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
fix: allow overriding replace in guards
authorEduardo San Martin Morote <posva13@gmail.com>
Wed, 13 Jul 2022 08:50:36 +0000 (10:50 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Wed, 13 Jul 2022 08:50:53 +0000 (10:50 +0200)
Fix #1471

packages/router/__tests__/router.spec.ts
packages/router/src/router.ts

index bd6b007009f866e0e4f04fca9723bad6f4065db2..016becc4ef789892537628baa0bf21a7df77efa2 100644 (file)
@@ -143,11 +143,31 @@ describe('Router', () => {
     // move somewhere else
     await router.push('/search')
     jest.spyOn(history, 'replace')
+    jest.spyOn(history, 'push')
     await router.replace('/home-before')
+    expect(history.push).toHaveBeenCalledTimes(0)
     expect(history.replace).toHaveBeenCalledTimes(1)
     expect(history.replace).toHaveBeenCalledWith('/', expect.anything())
   })
 
+  it('replaces if a guard redirect replaces', async () => {
+    const history = createMemoryHistory()
+    const { router } = await newRouter({ history })
+    // move somewhere else
+    router.beforeEach(to => {
+      if (to.name !== 'Foo') {
+        return { name: 'Foo', replace: true }
+      }
+    })
+    jest.spyOn(history, 'replace')
+    jest.spyOn(history, 'push')
+    await router.push('/search')
+    expect(history.location).toBe('/foo')
+    expect(history.push).toHaveBeenCalledTimes(0)
+    expect(history.replace).toHaveBeenCalledTimes(1)
+    expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
+  })
+
   it('allows to customize parseQuery', async () => {
     const parseQuery = jest.fn(_ => ({}))
     const { router } = await newRouter({ parseQuery })
index e44946c23897df1888ce86131f1e6d1af5487a89..bd938c0dc925b7efa6fed45e6eddf80eeeb1f4a8 100644 (file)
@@ -728,11 +728,17 @@ export function createRouter(options: RouterOptions): Router {
 
             return pushWithRedirect(
               // keep options
-              assign(locationAsObject(failure.to), {
-                state: data,
-                force,
-                replace,
-              }),
+              assign(
+                {
+                  // preserve an existing replace but allow the redirect to override it
+                  replace,
+                },
+                locationAsObject(failure.to),
+                {
+                  state: data,
+                  force,
+                }
+              ),
               // preserve the original redirectedFrom if any
               redirectedFrom || toLocation
             )