Skip to content

How to mock mitt to run tests in Jest? #199

@victormedeiros1

Description

@victormedeiros1

Hi, I'm trying to create a mock of mitt for the unit tests of my components in Vue 3, however, I'm not succeeding, can you help?

mitt instance file (in root):

import mitt from 'mitt'

export const emitirGlobal = mitt()

In my componente A:

import { emitirGlobal } from "@/mitt"

{ ... }

emitirGlobal.emit("recarregarAtividades")

In my componente B:

import { emitirGlobal } from "@/mitt"

{...}

emitirGlobal.on("recarregarAtividades", async (): Promise<void> => {
  await recarregarAtividades()
})

My archive jest-setup.ts:

import '@testing-library/jest-dom'
import { config } from '@vue/test-utils'
import i18n from '@/i18n'

config.global.plugins = [i18n]

jest.mock('mitt', () => {
  const emitirGlobal = {
    on: jest.fn(),
    emit: jest.fn(),
  }
  return { emitirGlobal }
})

global.console = {
  ...console,
  warn: jest.fn(),
  error: jest.fn(),
}

module.exports = {
  // Outras configurações do Jest...
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
};

I've also tried adding "mitt" to Jest's "plugins", but it didn't work:

import '@testing-library/jest-dom'
import { config } from '@vue/test-utils'
import i18n from '@/i18n'
import mitt from 'mitt'

config.global.plugins = [i18n, mitt()]

global.console = {
  ...console,
  warn: jest.fn(),
  error: jest.fn(),
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions