Skip to content

Commit

Permalink
fix(runtime-core): trigger warning when the injectionKey is undefined (
Browse files Browse the repository at this point in the history
…#760)

Co-authored-by: webfansplz <>
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
webfansplz and antfu committed Jul 15, 2021
1 parent 40cb14a commit 2ccad9b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/apis/inject.ts
Expand Up @@ -48,17 +48,18 @@ export function inject(
defaultValue?: unknown,
treatDefaultAsFactory = false
) {
if (!key) {
return defaultValue
}

const vm = getCurrentInstance()?.proxy
if (!vm) {
__DEV__ &&
warn(`inject() can only be used inside setup() or functional components.`)
return
}

if (!key) {
__DEV__ && warn(`injection "${String(key)}" not found.`, vm)
return defaultValue
}

const val = resolveInject(key, vm)
if (val !== NOT_FOUND) {
return val
Expand Down
22 changes: 22 additions & 0 deletions test/v3/runtime-core/apiInject.spec.ts
Expand Up @@ -242,6 +242,28 @@ describe('api: provide/inject', () => {
expect(`[Vue warn]: Injection "foo" not found`).toHaveBeenWarned()
})

it('should warn unfound w/ injectionKey is undefined', () => {
const Provider = {
setup() {
return () => h(Consumer)
},
}

const Consumer = {
setup() {
// The emulation does not use TypeScript
const foo = inject(undefined as unknown as string)
expect(foo).toBeUndefined()
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(`[Vue warn]: injection "undefined" not found.`).toHaveBeenWarned()
})

it('should not self-inject', () => {
const Comp = {
setup() {
Expand Down

0 comments on commit 2ccad9b

Please sign in to comment.