diff --git a/src/apis/inject.ts b/src/apis/inject.ts index 44183798..75b53013 100644 --- a/src/apis/inject.ts +++ b/src/apis/inject.ts @@ -48,10 +48,6 @@ export function inject( defaultValue?: unknown, treatDefaultAsFactory = false ) { - if (!key) { - return defaultValue - } - const vm = getCurrentInstance()?.proxy if (!vm) { __DEV__ && @@ -59,6 +55,11 @@ export function inject( return } + if (!key) { + __DEV__ && warn(`injection "${String(key)}" not found.`, vm) + return defaultValue + } + const val = resolveInject(key, vm) if (val !== NOT_FOUND) { return val diff --git a/test/v3/runtime-core/apiInject.spec.ts b/test/v3/runtime-core/apiInject.spec.ts index f4593eae..1ed7d5cb 100644 --- a/test/v3/runtime-core/apiInject.spec.ts +++ b/test/v3/runtime-core/apiInject.spec.ts @@ -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(`
`) + expect(`[Vue warn]: injection "undefined" not found.`).toHaveBeenWarned() + }) + it('should not self-inject', () => { const Comp = { setup() {