vuejs / apollo

🚀 Apollo/GraphQL integration for VueJS
http://apollo.vuejs.org
MIT License
6k stars 517 forks source link

Mocking `useQuery` in vue 3 composition api components #1266

Open hinogi opened 2 years ago

hinogi commented 2 years ago

Is your feature request related to a problem? Please describe. There is no testing example for vue3 composition api to test components that use useQuery.

Describe the solution you'd like Add an example on how to test with useQuery with vue3 composition api and jest and vue test utils.

paltman commented 2 years ago

Specifically, I'd love to know how to be able to use fixture data on my onResult handler. e.g. https://gist.github.com/paltman/517fc4d08747c5d313894ebf358e5c7c

mobsean commented 2 years ago

Specifically, I'd love to know how to be able to use fixture data on my onResult handler. e.g. https://gist.github.com/paltman/517fc4d08747c5d313894ebf358e5c7c

Hi, this was exactly my concern.

Since i won´t mock onResult, I wrote a component method that will be called by onResult.

I came up with this solution for unit tests:

onResult((res) => {
  handleOnResult(res)
})

const handleOnResult = (res) => {
  console.log('onResult have been called!')
  if (res.data === undefined) {
    return
  }
  //do some stuff here
}

Then you can unit test the method with different parameters...

    test('handleOnResult: undefined', () => {
      const spy = jest.spyOn(wrapper.vm, 'handleOnResult')
      const res = { data: undefined }
      vm.handleOnResult(res)
      expect(spy).toHaveBeenCalledTimes(1)
    })

Hope that helps. Have a nice day!