Navigation Menu

Skip to content

Commit

Permalink
fix(inject): allow default value to be undefined (#930)
Browse files Browse the repository at this point in the history
  • Loading branch information
seanogdev committed May 5, 2022
1 parent d8a8681 commit 17d3fc1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
14 changes: 6 additions & 8 deletions src/apis/inject.ts
Expand Up @@ -74,13 +74,11 @@ export function inject(
const val = resolveInject(key, vm)
if (val !== NOT_FOUND) {
return val
} else if (arguments.length > 1) {
return treatDefaultAsFactory && isFunction(defaultValue)
? defaultValue()
: defaultValue
} else if (__DEV__) {
warn(`Injection "${String(key)}" not found.`, vm)
}

if (defaultValue === undefined && __DEV__) {
warn(`Injection "${String(key)}" not found`, vm)
}

return treatDefaultAsFactory && isFunction(defaultValue)
? defaultValue()
: defaultValue
}
29 changes: 28 additions & 1 deletion test/v3/runtime-core/apiInject.spec.ts
Expand Up @@ -239,7 +239,7 @@ describe('api: provide/inject', () => {
const root = document.createElement('div')
const vm = createApp(Provider).mount(root)
expect(vm.$el.outerHTML).toBe(`<div></div>`)
expect(`[Vue warn]: Injection "foo" not found`).toHaveBeenWarned()
expect(`[Vue warn]: Injection "foo" not found.`).toHaveBeenWarned()
})

it('should warn unfound w/ injectionKey is undefined', () => {
Expand Down Expand Up @@ -277,4 +277,31 @@ describe('api: provide/inject', () => {
const vm = createApp(Comp).mount(root)
expect(vm.$el.outerHTML).toBe(`<div>foo</div>`)
})

it('should not warn when default value is undefined', () => {
const Provider = {
setup() {
provide('foo', undefined)
return () => h(Middle)
},
}

const Middle = {
setup() {
return () => h(Consumer)
},
}

const Consumer = {
setup() {
const foo = inject('foo')
return () => h('div', foo as unknown as string)
},
}

const root = document.createElement('div')
const vm = createApp(Provider).mount(root)
expect(vm.$el.outerHTML).toBe(`<div></div>`)
expect(`injection "foo" not found.`).not.toHaveBeenWarned()
})
})

0 comments on commit 17d3fc1

Please sign in to comment.