Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(runtime-core): trigger warning when the injectionKey is undefined #760

Merged
merged 6 commits into from Jul 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/apis/inject.ts
Expand Up @@ -48,17 +48,18 @@ export function inject(
defaultValue?: unknown,
treatDefaultAsFactory = false
) {
if (!key) {
return defaultValue
}

const vm = getCurrentInstance()?.proxy
if (!vm) {
__DEV__ &&
warn(`inject() can only be used inside setup() or functional components.`)
return
}

if (!key) {
__DEV__ && warn(`injection "${String(key)}" not found.`, vm)
return defaultValue
}

const val = resolveInject(key, vm)
if (val !== NOT_FOUND) {
return val
Expand Down
22 changes: 22 additions & 0 deletions test/v3/runtime-core/apiInject.spec.ts
Expand Up @@ -242,6 +242,28 @@ describe('api: provide/inject', () => {
expect(`[Vue warn]: Injection "foo" not found`).toHaveBeenWarned()
})

it('should warn unfound w/ injectionKey is undefined', () => {
const Provider = {
setup() {
return () => h(Consumer)
},
}

const Consumer = {
setup() {
// The emulation does not use TypeScript
const foo = inject(undefined as unknown as string)
expect(foo).toBeUndefined()
return () => h('div', foo as unknown as string)
},
}

const root = document.createElement('div')
const vm = createApp(Provider).mount(root)
expect(vm.$el.outerHTML).toBe(`<div></div>`)
expect(`[Vue warn]: injection "undefined" not found.`).toHaveBeenWarned()
})

it('should not self-inject', () => {
const Comp = {
setup() {
Expand Down