]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
test: test onBeforeRouteLeave
authorEduardo San Martin Morote <posva13@gmail.com>
Tue, 28 Apr 2020 08:58:37 +0000 (10:58 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Tue, 28 Apr 2020 08:58:37 +0000 (10:58 +0200)
__tests__/guards/onBeforeRouteLeave.spec.ts [new file with mode: 0644]

diff --git a/__tests__/guards/onBeforeRouteLeave.spec.ts b/__tests__/guards/onBeforeRouteLeave.spec.ts
new file mode 100644 (file)
index 0000000..6ec2257
--- /dev/null
@@ -0,0 +1,55 @@
+/**
+ * @jest-environment jsdom
+ */
+import {
+  createRouter,
+  createMemoryHistory,
+  onBeforeRouteLeave,
+} from '../../src'
+import { createApp, defineComponent } from 'vue'
+
+const component = {
+  template: '<div>Generic</div>',
+}
+
+describe('onBeforeRouteLeave', () => {
+  it('invokes with the component context', async () => {
+    expect.assertions(2)
+    const spy = jest
+      .fn()
+      .mockImplementationOnce(function (this: any, to, from, next) {
+        expect(typeof this.counter).toBe('number')
+        next()
+      })
+    const WithLeave = defineComponent({
+      template: `text`,
+      // we use data to check if the context is the right one because saving `this` in a variable logs a few warnings
+      data: () => ({ counter: 0 }),
+      setup() {
+        onBeforeRouteLeave(spy)
+      },
+    })
+
+    const router = createRouter({
+      history: createMemoryHistory(),
+      routes: [
+        { path: '/', component },
+        { path: '/leave', component: WithLeave as any },
+      ],
+    })
+    const app = createApp({
+      template: `
+      <router-view />
+      `,
+    })
+    app.use(router)
+    const rootEl = document.createElement('div')
+    document.body.appendChild(rootEl)
+    app.mount(rootEl)
+
+    await router.isReady()
+    await router.push('/leave')
+    await router.push('/')
+    expect(spy).toHaveBeenCalledTimes(1)
+  })
+})