From 17d3fc120b396e460463dccc5244b3c1fe9a84a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Se=C3=A1n=20O=27Grady?= <1761115+miralize@users.noreply.github.com> Date: Thu, 5 May 2022 18:07:50 +0100 Subject: [PATCH] fix(inject): allow default value to be undefined (#930) --- src/apis/inject.ts | 14 ++++++------- test/v3/runtime-core/apiInject.spec.ts | 29 +++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/apis/inject.ts b/src/apis/inject.ts index e94c7a2b..37ed881d 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 1ed7d5cb..99b7cc85 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() + }) })