Skip to content

Commit b182ac4

Browse files
maciej-kayyx990803
authored andcommitted
Warn when a inject has been not provided (#5681)
* warn when a inject has been not provided * typo * typo * fix when undefined is provided * use util hasOwn * refactor * test case * Revert "test case" This reverts commit 08f0a8b. * test case
1 parent e274c96 commit b182ac4

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/core/instance/inject.js

+4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import { hasSymbol } from 'core/util/env'
44
import { warn } from '../util/index'
55
import { defineReactive } from '../observer/index'
6+
import { hasOwn } from 'shared/util'
67

78
export function initProvide (vm: Component) {
89
const provide = vm.$options.provide
@@ -57,6 +58,9 @@ export function resolveInject (inject: any, vm: Component): ?Object {
5758
}
5859
source = source.$parent
5960
}
61+
if (process.env.NODE_ENV !== 'production' && !hasOwn(result, key)) {
62+
warn(`Injection "${key}" not found`, vm)
63+
}
6064
}
6165
return result
6266
}

test/unit/features/options/inject.spec.js

+29
Original file line numberDiff line numberDiff line change
@@ -240,4 +240,33 @@ describe('Options provide/inject', () => {
240240
`overwritten whenever the provided component re-renders. ` +
241241
`injection being mutated: "${key}"`).toHaveBeenWarned()
242242
})
243+
244+
it('should warn when injections cannot be found', () => {
245+
const vm = new Vue({})
246+
new Vue({
247+
parent: vm,
248+
inject: ['foo', 'bar'],
249+
created () {}
250+
})
251+
expect(`Injection "foo" not found`).toHaveBeenWarned()
252+
expect(`Injection "bar" not found`).toHaveBeenWarned()
253+
})
254+
255+
it('should not warn when injections can be found', () => {
256+
const vm = new Vue({
257+
provide: {
258+
foo: 1,
259+
bar: false,
260+
baz: undefined
261+
}
262+
})
263+
new Vue({
264+
parent: vm,
265+
inject: ['foo', 'bar', 'baz'],
266+
created () {}
267+
})
268+
expect(`Injection "foo" not found`).not.toHaveBeenWarned()
269+
expect(`Injection "bar" not found`).not.toHaveBeenWarned()
270+
expect(`Injection "baz" not found`).not.toHaveBeenWarned()
271+
})
243272
})

0 commit comments

Comments
 (0)