Share single implementation of jest mocked module across multiple tests

Viewed 276

Context

I want to share a mocked module across multiple tests without having to copy and paste the custom implementation all the time.

We use the next-i18next library to handle our translations and with it comes a hook called useTranslations() which returns the t function. Generally it gets called as follows:

// SomeComponent.tsx
export const SomeComponent: FunctionComponent = () => {
...   
  const { t } = useTranslation('common')
...
}

When testing SomeComponent.tsx the setup generally looks as follows with the useTranslations() hook mocked out using jest.mock(...) at the top of the file below the imports.

// SomeComponent.test.tsx

// imports

jest.mock('next-i18next', () => ({
  useTranslation: () => ({
    t: (e) => e
  })
}))


describe('SomeComponent tests', () => {
  
  test('should do something', () => {
    ...
  })
})

This works quite well with the exception that I have to copy and paste the jest.mock(...) section in every test where the useTranslation() hook is used. We have a lot of components and a lot of them use useTranslation

Actual Issue

I've tried following the guide set out here by using the __mocks__ folder approach: https://jestjs.io/docs/manual-mocks

My directory structure has been setup to look something like this:

...
├── node_modules
├── __mocks__
│   └── next-i18next.ts
├── src
    └──SomeComponent
       ├── SomeComponent.test.tsx
       └── SomeComponent.tsx
├── other.ts
...

and I've then added a simple jest.mock at the top of the SomeComponent.test.tsx file so that it looks like this

// SomeComponent.test.tsx

// imports

jest.mock('next-i18next')

describe('SomeComponent tests', () => {
  
  test('should do something', () => {
    ...
  })
})

But it doesn't really work and I always seem to run into the following error:

TypeError: (0 , _nextI18next.useTranslation) is not a function

Any ideas of how to do this?

Edit

For the mock I essentially tried doing what they demonstrated in the docs with fs

// __mocks__/next-i18next.ts

const nexti18next = jest.createMockFromModule('next-i18next')

nexti18next.useTranslation = () => ({
   t: (e) => e
})

module.exports = nexti18next
0 Answers
Related