nuxt-community / composition-api

Composition API hooks for Nuxt 2.
https://composition-api.nuxtjs.org
MIT License
705 stars 100 forks source link

help: Plugins Inject Unit Test #576

Open ariefsn opened 2 years ago

ariefsn commented 2 years ago

📚 What are you trying to do? Please describe. Hi, how to mock injection? injection was working fine, but its become undefined when running test. Nuxt2 + Typescript + CompositionApi

// plugins/myPlugin.ts
const utility: Plugin = (context, inject) => {
  inject('myFunc', (str: string) => str)
}

export default utility
// components/MyComponent.vue
setup() {
   const { $myFunc } = useContext()

   onMounted(() => {
      console.log('myFunc', $myfunc) // will print undefined on testing
   })
}
// test/MyComponent.spec.ts
const wrapper = mount(MyComponent, {
   localVue,
   mocks: {
      $myFunc: (str: string) => str
   }
})

🔍 What have you tried? Have mocks in options, still not works.

ℹī¸ Additional context

BryceBarbara commented 5 months ago

I would mock the return value of useContext(). The exact approach will differ depending on the testing library you're using. My examples with be when using Vitest.

To mock it when it's used as a global:

const useContextMock: Mock<any, any> = vi.fn().mockImplementation(() => {
  return { $myFunc: (str: string) => str }
})
vi.stubGlobal('useContext', useContextMock)

// And to change the implementation for a specific test
useContextMock.mockImplementation(() => {
  return { $myFunc: (str: string) => `Changed - ${str}` }
})

To mock it when it's imported directly:

import { useContext } from '@nuxtjs/composition-api'

vi.mock('@nuxtjs/composition-api', () => {
  return {
    useContext: vi.fn().mockImplementation(() => {
      return { $myFunc: (str: string) => str }
    }),
  }
})

// And to change the implementation for a specific test
vi.mocked(useContext).mockImplementation(() => {
  return { $myFunc: (str: string) => `Changed - ${str}` }
})