u3u / vue-hooks

⚡️Awesome Vue Hooks
https://vue-hooks.netlify.com
MIT License
493 stars 33 forks source link

How can we mount components with vue-hooks in unit test #184

Closed hiiwave closed 4 years ago

hiiwave commented 4 years ago

Hi, great thanks for this amazing project!

I tried to unit test my component with vue-hooks using vue-test-utils. When I mount my component, I got [vue-hooks] Not found vue instance error. I think I need a mock regarding vuex to do it, but I have no clue how to do so. Could you please guide us how we can provide a mocked hooks in order to unit test components based on them? Thanks a lot.

issue-label-bot[bot] commented 4 years ago

Issue-Label Bot is automatically applying the label question to this issue, with a confidence of 0.92. Please mark this comment with :thumbsup: or :thumbsdown: to give our bot feedback!

Links: app homepage, dashboard and code for this bot.

hiiwave commented 4 years ago

It turns out that I should do Vue.use(hooks) in my test setup as well. Then I can test my component with either real vuex or mocked vuex correctly.

daiyadove commented 4 years ago

@hiiwave Hi, I'm having the same problem. Can you write a sample of successfu testl code if possible?

hiiwave commented 4 years ago

I added that line Vue.use(hooks) in setup.js, which was specified by setupFiles in jest.config.js

daiyadove commented 4 years ago

@hiiwave

I added that line Vue.use(hooks) in setup.js, which was specified by setupFiles in jest.config.js

Thank you. I did it based on your advice. I'm doing it the way below because I'm creating a Vue environment for each test case in my environment (I think the behavior is the same as yours). But it's not working. What is the problem?

// useHoge.spec.ts
import VueCompositionApi from '@vue/composition-api'
import { createLocalVue } from '@vue/test-utils'
import useHoge from '@/use/useHoge'
import hooks from '@u3u/vue-hooks'

const localVue = createLocalVue()
localVue.use(VueCompositionApi)
localVue.use(hooks)
describe('useMaterial', () => {
  it('define', () => {
    expect(useHoge).toBeDefined() // pass
  })
  it('creted', () => {
    const { state } = useHoge() // ReferenceError: [vue-hooks] Not found vue instance.
  })
})
// useHoge.ts
import { useStore } from '@u3u/vue-hooks'
const useHoge = () => {
  const store = useStore()
}
export default useHoge
hiiwave commented 4 years ago

I have no idea why localVue does not work for you so far. May you try first if using global vue instance works for you?

daiyadove commented 4 years ago

May you try first if using global vue instance works for you?

I tried that, but it didn't work.

hiiwave commented 4 years ago

I did not call hooks in testing code; instead, I only call them under setup function inside component. My component is mounted by mount in testing code. My best guess is that maybe hooks can only be called inside component?

It would be great if @u3u have time to comment.