const expect = require('expect')
const { HTML5History } = require('../src/history/html5')
const { Router } = require('../src/router')
-const { JSDOM } = require('jsdom')
+const { createDom, components } = require('./utils')
+
+function mockHistory() {
+ // TODO: actually do a mock
+ return new HTML5History()
+}
+
+const routes = [
+ { path: '/', component: components.Home },
+ { path: '/foo', component: components.Foo },
+]
describe('Router', () => {
beforeAll(() => {
- // TODO: move to utils for tests that need DOM
- const dom = new JSDOM(
- `<!DOCTYPE html><html><head></head><body></body></html>`,
- {
- url: 'https://example.org/',
- referrer: 'https://example.com/',
- contentType: 'text/html',
- }
- )
-
- // @ts-ignore
- global.window = dom.window
+ createDom()
})
it('can be instantiated', () => {
- const history = new HTML5History()
- const router = new Router({ history, routes: [] })
+ const history = mockHistory()
+ const router = new Router({ history, routes })
expect(router.currentRoute).toEqual({
fullPath: '/',
hash: '',
query: {},
})
})
+
+ it('calls history.push with router.push', async () => {
+ const history = mockHistory()
+ const router = new Router({ history, routes })
+ jest.spyOn(history, 'push')
+ await router.push('/foo')
+ expect(history.push).toHaveBeenCalledTimes(1)
+ expect(history.push).toHaveBeenCalledWith({
+ fullPath: '/foo',
+ path: '/foo',
+ query: {},
+ hash: '',
+ })
+ })
+
+ it('calls history.replace with router.replace', async () => {
+ const history = mockHistory()
+ const router = new Router({ history, routes })
+ jest.spyOn(history, 'replace')
+ await router.replace('/foo')
+ expect(history.replace).toHaveBeenCalledTimes(1)
+ expect(history.replace).toHaveBeenCalledWith({
+ fullPath: '/foo',
+ path: '/foo',
+ query: {},
+ hash: '',
+ })
+ })
})
}
/**
- * Trigger a navigation, should resolve all guards first
- * @param to Where to go
+ * Trigger a navigation, adding an entry to the history stack. Also apply all navigation
+ * guards first
+ * @param to where to go
*/
async push(to: RouteLocation) {
let url: HistoryLocationNormalized
// TODO: refactor in a function, some kind of queue
const toLocation: RouteLocationNormalized = { ...url, ...location }
await this.navigate(toLocation, this.currentRoute)
- this.history.push(url)
+ if (to.replace === true) this.history.replace(url)
+ else this.history.push(url)
const from = this.currentRoute
this.currentRoute = toLocation
for (const guard of this.afterGuards) guard(toLocation, from)
}
+ /**
+ * Trigger a navigation, replacing current entry in history. Also apply all navigation
+ * guards first
+ * @param to where to go
+ */
replace(to: RouteLocation) {
const location = typeof to === 'string' ? { path: to } : to
return this.push({ ...location, replace: true })