Explorar o código

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 08f0a8b6c3837fc34ddd264712b8c30a05c165e5.

* test case
Maciej Kasprzyk %!s(int64=9) %!d(string=hai) anos
pai
achega
b182ac4069
Modificáronse 2 ficheiros con 33 adicións e 0 borrados
  1. 4 0
      src/core/instance/inject.js
  2. 29 0
      test/unit/features/options/inject.spec.js

+ 4 - 0
src/core/instance/inject.js

@@ -3,6 +3,7 @@
 import { hasSymbol } from 'core/util/env'
 import { warn } from '../util/index'
 import { defineReactive } from '../observer/index'
+import { hasOwn } from 'shared/util'
 
 export function initProvide (vm: Component) {
   const provide = vm.$options.provide
@@ -57,6 +58,9 @@ export function resolveInject (inject: any, vm: Component): ?Object {
         }
         source = source.$parent
       }
+      if (process.env.NODE_ENV !== 'production' && !hasOwn(result, key)) {
+        warn(`Injection "${key}" not found`, vm)
+      }
     }
     return result
   }

+ 29 - 0
test/unit/features/options/inject.spec.js

@@ -240,4 +240,33 @@ describe('Options provide/inject', () => {
       `overwritten whenever the provided component re-renders. ` +
       `injection being mutated: "${key}"`).toHaveBeenWarned()
   })
+
+  it('should warn when injections cannot be found', () => {
+    const vm = new Vue({})
+    new Vue({
+      parent: vm,
+      inject: ['foo', 'bar'],
+      created () {}
+    })
+    expect(`Injection "foo" not found`).toHaveBeenWarned()
+    expect(`Injection "bar" not found`).toHaveBeenWarned()
+  })
+
+  it('should not warn when injections can be found', () => {
+    const vm = new Vue({
+      provide: {
+        foo: 1,
+        bar: false,
+        baz: undefined
+      }
+    })
+    new Vue({
+      parent: vm,
+      inject: ['foo', 'bar', 'baz'],
+      created () {}
+    })
+    expect(`Injection "foo" not found`).not.toHaveBeenWarned()
+    expect(`Injection "bar" not found`).not.toHaveBeenWarned()
+    expect(`Injection "baz" not found`).not.toHaveBeenWarned()
+  })
 })