File tree Expand file tree Collapse file tree 2 files changed +27
-4
lines changed Expand file tree Collapse file tree 2 files changed +27
-4
lines changed Original file line number Diff line number Diff line change @@ -48,17 +48,18 @@ export function inject(
4848 defaultValue ?: unknown ,
4949 treatDefaultAsFactory = false
5050) {
51- if ( ! key ) {
52- return defaultValue
53- }
54-
5551 const vm = getCurrentInstance ( ) ?. proxy
5652 if ( ! vm ) {
5753 __DEV__ &&
5854 warn ( `inject() can only be used inside setup() or functional components.` )
5955 return
6056 }
6157
58+ if ( ! key ) {
59+ __DEV__ && warn ( `injection "${ String ( key ) } " not found.` , vm )
60+ return defaultValue
61+ }
62+
6263 const val = resolveInject ( key , vm )
6364 if ( val !== NOT_FOUND ) {
6465 return val
Original file line number Diff line number Diff line change @@ -242,6 +242,28 @@ describe('api: provide/inject', () => {
242242 expect ( `[Vue warn]: Injection "foo" not found` ) . toHaveBeenWarned ( )
243243 } )
244244
245+ it ( 'should warn unfound w/ injectionKey is undefined' , ( ) => {
246+ const Provider = {
247+ setup ( ) {
248+ return ( ) => h ( Consumer )
249+ } ,
250+ }
251+
252+ const Consumer = {
253+ setup ( ) {
254+ // The emulation does not use TypeScript
255+ const foo = inject ( undefined as unknown as string )
256+ expect ( foo ) . toBeUndefined ( )
257+ return ( ) => h ( 'div' , foo as unknown as string )
258+ } ,
259+ }
260+
261+ const root = document . createElement ( 'div' )
262+ const vm = createApp ( Provider ) . mount ( root )
263+ expect ( vm . $el . outerHTML ) . toBe ( `<div></div>` )
264+ expect ( `[Vue warn]: injection "undefined" not found.` ) . toHaveBeenWarned ( )
265+ } )
266+
245267 it ( 'should not self-inject' , ( ) => {
246268 const Comp = {
247269 setup ( ) {
You can’t perform that action at this time.
0 commit comments