Jest, Vue3 and Typescript: How to mock injection by symbol?

Viewed 1222

I have this situation:

// symbols.ts - Injection Key defined as a Symbol
export const FAQ_SERVICE: InjectionKey<FAQService> = Symbol('FAQService');

// main.ts - globally provides a service using the injection key
app.provide(FAQ_SERVICE, new FAQService());

// FAQIndex.vue - component using the injected service
…
setup() {
  return {
    faqService: inject(FAQ_SERVICE) as FAQService,
  };
}
…

Now I want to test this component using jest and mock the service. I know that when I provide objects using plain Strings, I can do this via this pattern:

component = mount(FAQIndex, {
  global: {
    provide: {
      'FAQ_SERVICE': { /* mock object */ },
    },
  },
});

But how can I do this when the service is injected via Symbols as in the example above?

1 Answers

Import FAQ_SERVICE in your test just like your app does:

import { FAQ_SERVICE } from './symbols'

it('does something', () => {
  const component = mount(FAQIndex, {
    global: {
      provide: {
        [FAQ_SERVICE as symbol]: { /* mock object */ }
      }
    }
  })
})
Related