2017-02-15 08:52:22 +00:00
|
|
|
/* global describe, it, expect */
|
2018-10-01 22:55:31 +00:00
|
|
|
import Router from 'next-server/dist/lib/router/router'
|
2017-02-15 08:52:22 +00:00
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
class PageLoader {
|
|
|
|
constructor (options = {}) {
|
|
|
|
this.options = options
|
|
|
|
this.loaded = {}
|
|
|
|
}
|
|
|
|
|
|
|
|
loadPage (route) {
|
|
|
|
this.loaded[route] = true
|
|
|
|
|
|
|
|
if (this.options.delay) {
|
|
|
|
return new Promise((resolve) => setTimeout(resolve, this.options.delay))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-15 08:52:22 +00:00
|
|
|
describe('Router', () => {
|
2017-02-17 04:12:32 +00:00
|
|
|
const request = { clone: () => null }
|
2017-02-15 08:52:22 +00:00
|
|
|
describe('.prefetch()', () => {
|
|
|
|
it('should prefetch a given page', async () => {
|
2017-05-09 07:42:48 +00:00
|
|
|
global.__NEXT_DATA__ = {}
|
2017-04-18 04:18:43 +00:00
|
|
|
const pageLoader = new PageLoader()
|
|
|
|
const router = new Router('/', {}, '/', { pageLoader })
|
|
|
|
const route = '/routex'
|
2017-02-15 08:52:22 +00:00
|
|
|
await router.prefetch(route)
|
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
expect(pageLoader.loaded['/routex']).toBeTruthy()
|
2017-02-15 08:52:22 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
it('should only run two jobs at a time', async () => {
|
2017-05-09 07:42:48 +00:00
|
|
|
global.__NEXT_DATA__ = {}
|
2017-04-18 04:18:43 +00:00
|
|
|
// delay loading pages for an hour
|
|
|
|
const pageLoader = new PageLoader({ delay: 1000 * 3600 })
|
|
|
|
const router = new Router('/', {}, '/', { pageLoader })
|
2017-02-15 08:52:22 +00:00
|
|
|
|
|
|
|
router.prefetch('route1')
|
|
|
|
router.prefetch('route2')
|
|
|
|
router.prefetch('route3')
|
|
|
|
router.prefetch('route4')
|
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
// Wait for a bit
|
2017-02-15 08:52:22 +00:00
|
|
|
await new Promise((resolve) => setTimeout(resolve, 50))
|
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
expect(Object.keys(pageLoader.loaded).length).toBe(2)
|
|
|
|
expect(Object.keys(pageLoader.loaded)).toEqual(['route1', 'route2'])
|
2017-02-15 08:52:22 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
it('should run all the jobs', async () => {
|
2017-05-09 07:42:48 +00:00
|
|
|
global.__NEXT_DATA__ = {}
|
2017-04-18 04:18:43 +00:00
|
|
|
const pageLoader = new PageLoader()
|
|
|
|
const router = new Router('/', {}, '/', { pageLoader })
|
2017-02-15 08:52:22 +00:00
|
|
|
const routes = ['route1', 'route2', 'route3', 'route4']
|
|
|
|
|
2017-02-17 04:12:32 +00:00
|
|
|
router.doFetchRoute = () => Promise.resolve(request)
|
2017-02-15 08:52:22 +00:00
|
|
|
|
|
|
|
await router.prefetch(routes[0])
|
|
|
|
await router.prefetch(routes[1])
|
|
|
|
await router.prefetch(routes[2])
|
|
|
|
await router.prefetch(routes[3])
|
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
expect(Object.keys(pageLoader.loaded)).toEqual(routes)
|
2017-02-15 08:52:22 +00:00
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|