Skip to content

Commit 2ccad9b

Browse files
webfansplzantfu
andauthored
fix(runtime-core): trigger warning when the injectionKey is undefined (#760)
Co-authored-by: webfansplz <> Co-authored-by: Anthony Fu <[email protected]>
1 parent 40cb14a commit 2ccad9b

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/apis/inject.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff 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

test/v3/runtime-core/apiInject.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff 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() {

0 commit comments

Comments
 (0)