fix(app): Throw error only if value is undefined (#4206)

This commit is contained in:
Paul Gascou-Vaillancourt 2018-10-27 12:41:42 -04:00 committed by Pooya Parsa
parent 1adad4676b
commit 208eba3867
4 changed files with 35 additions and 2 deletions

View File

@ -130,7 +130,7 @@ async function createApp(ssrContext) {
<% if (plugins.length) { %>
const inject = function (key, value) {
if (!key) throw new Error('inject(key, value) has no key provided')
if (!value) throw new Error('inject(key, value) has no value provided')
if (typeof value === 'undefined') throw new Error('inject(key, value) has no value provided')
key = '$' + key
// Add into app
app[key] = value

View File

@ -63,7 +63,8 @@ export default {
transition: false,
plugins: [
'~/plugins/vuex-module',
'~/plugins/dir-plugin'
'~/plugins/dir-plugin',
'~/plugins/inject'
],
build: {
scopeHoisting: true,

16
test/fixtures/basic/plugins/inject.js vendored Normal file
View File

@ -0,0 +1,16 @@
export default ({ route, params }, inject) => {
const { injectValue } = route.query
if (typeof injectValue === 'undefined') {
return
}
const key = 'injectedProperty'
const map = {
'undefined': undefined,
'null': null,
'false': false,
'0': 0,
'empty': ''
}
const value = map[injectValue]
inject(key, value)
}

View File

@ -18,6 +18,22 @@ describe('with-config', () => {
expect(window.__test_plugin).toBe(true)
})
test('inject fails if value is undefined', async () => {
// inject('injectedProperty', undefined)
await expect(nuxt.renderRoute('/?injectValue=undefined')).rejects.toThrowError('inject(key, value) has no value provided')
})
test('inject succeeds if value is defined but evaluates to false', async () => {
// inject('injectedProperty', null)
await expect(nuxt.renderRoute('/?injectValue=null')).resolves.not.toThrowError()
// inject('injectedProperty', false)
await expect(nuxt.renderRoute('/?injectValue=false')).resolves.not.toThrowError()
// inject('injectedProperty', 0)
await expect(nuxt.renderRoute('/?injectValue=0')).resolves.not.toThrowError()
// inject('injectedProperty', '')
await expect(nuxt.renderRoute('/?injectValue=empty')).resolves.not.toThrowError()
})
// Close server and ask nuxt to stop listening to file changes
afterAll(async () => {
await nuxt.close()