shifty-router
Version:
Fast, modular client router
83 lines (74 loc) • 2.76 kB
JavaScript
import { expect } from 'chai'
import createLocation from '../create-location.js'
import window from 'global/window.js'
describe('create-location', () => {
let originalWindow, originalDocument
beforeEach(() => {
// Save originals
originalWindow = global.window
originalDocument = global.document
global.window = Object.assign({}, window) // use a copy
global.document = {
createElement: (tag) => {
if (tag === 'a') {
return {
set href (val) {
this._href = val
// Mocking simple URL parsing
if (val.startsWith('http')) {
const url = new URL(val)
this.pathname = url.pathname
this.search = url.search
this.hash = url.hash
} else if (val.startsWith('/')) {
this.pathname = val.split('?')[0].split('#')[0]
this.search = val.includes('?') ? '?' + val.split('?')[1].split('#')[0] : ''
this.hash = val.includes('#') ? '#' + val.split('#')[1] : ''
}
},
get href () { return this._href }
}
}
}
}
global.window.location = {
pathname: '/home',
search: '?foo=bar',
hash: '#hash',
href: 'http://localhost/home?foo=bar#hash'
}
})
afterEach(() => {
global.window = originalWindow
global.document = originalDocument
})
it('should return initial state when no state is provided', () => {
const loc = createLocation()
expect(loc.pathname).to.equal('/home')
expect(loc.search).to.deep.equal({ foo: 'bar' })
expect(loc.hash).to.equal('#hash')
expect(loc.href).to.equal('http://localhost/home?foo=bar#hash')
})
it('should patch state with a string', () => {
const state = { pathname: '/home', search: {}, hash: '', href: '' }
const loc = createLocation(state, '/new-path?baz=qux#new-hash')
expect(loc.pathname).to.equal('/new-path')
expect(loc.search).to.deep.equal({ baz: 'qux' })
expect(loc.hash).to.equal('#new-hash')
})
it('should patch state with an object', () => {
const state = { pathname: '/home', search: { foo: 'bar' }, hash: '#hash', href: '...' }
const patch = { pathname: '/new-home' }
const loc = createLocation(state, patch)
expect(loc.pathname).to.equal('/new-home')
expect(loc.search).to.deep.equal({ foo: 'bar' })
expect(loc.hash).to.equal('#hash')
})
it('should return default state when window is undefined', () => {
const originalWindow = global.window
delete global.window
const loc = createLocation()
expect(loc).to.deep.equal({ pathname: '', search: {}, hash: '', href: '' })
global.window = originalWindow
})
})