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: spy on wrapper.vm with Jest #310

Merged
merged 2 commits into from
Feb 25, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,11 @@ export function mount(
// if not, use the return value from app.mount.
const appRef = vm.$refs[MOUNT_COMPONENT_REF] as ComponentPublicInstance
const $vm = Reflect.ownKeys(appRef).length ? appRef : vm
// we add `hasOwnProperty` so jest can spy on the proxied vm without throwing
$vm.hasOwnProperty = (property) => {
return Reflect.has($vm, property)
}
console.warn = warnSave

return createWrapper(app, $vm, setProps)
}

Expand Down
21 changes: 21 additions & 0 deletions tests/vm.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,25 @@ describe('vm', () => {

expect(wrapper.vm.isEnabled).toBe(false)
})

it('allows spying on vm', async () => {
const Component = defineComponent({
name: 'VTUComponent',
template: '<div @click="toggle()">{{ msg }}</div>',
setup() {
const msg = 'hello'
const isEnabled = ref(true)
const toggle = () => (isEnabled.value = !isEnabled.value)
return { msg, isEnabled, toggle }
}
})

const wrapper = mount(Component)

jest.spyOn(wrapper.vm, 'toggle')

await wrapper.get('div').trigger('click')

expect(wrapper.vm.toggle).toHaveBeenCalled()
})
})