Skip to content

Commit

Permalink
Merge pull request #214 from vuejs/issue-211
Browse files Browse the repository at this point in the history
fix: allow finding root component
  • Loading branch information
lmiller1990 committed Sep 28, 2020
2 parents db9fb9a + 910e3f4 commit eec2d2d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/utils/find.ts
Expand Up @@ -13,7 +13,10 @@ import { matchName } from './matchName'
* @param selector
* @return {boolean | ((value: any) => boolean)}
*/
function matches(node: VNode, selector: FindAllComponentsSelector): boolean {
export function matches(
node: VNode,
selector: FindAllComponentsSelector
): boolean {
// do not return none Vue components
if (!node.component) return false

Expand Down Expand Up @@ -54,7 +57,9 @@ function matches(node: VNode, selector: FindAllComponentsSelector): boolean {
}
}
// we may have one or both missing names
return matchName(selectorName, componentName)
if (selectorName && componentName) {
return matchName(selectorName, componentName)
}
}
}

Expand Down
12 changes: 11 additions & 1 deletion src/vueWrapper.ts
Expand Up @@ -10,7 +10,7 @@ import {
} from './types'
import { createWrapperError } from './errorWrapper'
import { TriggerOptions } from './createDomEvent'
import { find } from './utils/find'
import { find, matches } from './utils/find'
import { isFunctionalComponent } from './utils'

export class VueWrapper<T extends ComponentPublicInstance> {
Expand Down Expand Up @@ -164,6 +164,16 @@ export class VueWrapper<T extends ComponentPublicInstance> {
})
}

// https://github.com/vuejs/vue-test-utils-next/issues/211
// VTU v1 supported finding the component mounted itself.
// eg: mount(Comp).findComponent(Comp)
// this is the same as doing `wrapper.vm`, but we keep this behavior for back compat.
if (matches(this.vm.$.vnode, selector)) {
return createWrapper(null, this.vm.$.vnode.component.proxy, {
isFunctionalComponent: false
})
}

return createWrapperError('VueWrapper')
}

Expand Down
18 changes: 18 additions & 0 deletions tests/findComponent.spec.ts
Expand Up @@ -28,6 +28,7 @@ const compB = defineComponent({
})

const compA = defineComponent({
name: 'A',
template: `
<div class="A">
<comp-b />
Expand Down Expand Up @@ -82,6 +83,23 @@ describe('findComponent', () => {
expect(wrapper.findComponent({ name: 'component-c' }).exists()).toBeTruthy()
})

it('finds root component', async () => {
const Comp = defineComponent({
name: 'C',
template: `
<input v-model="msg" />
{{ msg }}
`,
data() {
return { msg: 'foo' }
}
})
const wrapper = mount(Comp)
expect(wrapper.findComponent(Comp).exists()).toBe(true)
await wrapper.find('input').setValue('bar')
expect(wrapper.html()).toContain('bar')
})

it('finds component without a name by using its object definition', () => {
const Component = {
template: '<div><component-without-name/></div>',
Expand Down

0 comments on commit eec2d2d

Please sign in to comment.