diff --git a/src/apis/inject.ts b/src/apis/inject.ts index e94c7a2..37ed881 100644 --- a/src/apis/inject.ts +++ b/src/apis/inject.ts @@ -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 } diff --git a/test/v3/runtime-core/apiInject.spec.ts b/test/v3/runtime-core/apiInject.spec.ts index 1ed7d5c..99b7cc8 100644 --- a/test/v3/runtime-core/apiInject.spec.ts +++ b/test/v3/runtime-core/apiInject.spec.ts @@ -239,7 +239,7 @@ describe('api: provide/inject', () => { const root = document.createElement('div') const vm = createApp(Provider).mount(root) expect(vm.$el.outerHTML).toBe(`
`) - expect(`[Vue warn]: Injection "foo" not found`).toHaveBeenWarned() + expect(`[Vue warn]: Injection "foo" not found.`).toHaveBeenWarned() }) it('should warn unfound w/ injectionKey is undefined', () => { @@ -277,4 +277,31 @@ describe('api: provide/inject', () => { const vm = createApp(Comp).mount(root) expect(vm.$el.outerHTML).toBe(`
foo
`) }) + + 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(`
`) + expect(`injection "foo" not found.`).not.toHaveBeenWarned() + }) })