Dmitry McLygin
Dmitry McLygin

Reputation: 94

How to resolve module dependancies when mocking modules in JEST

I have a node module resolution. And have a next modules:

A/
  A.tsx
  index.ts
B/
  B.tsx
  index.ts
  text.tsx
// A/A.tsx

export const A = '1'
// A/index.tsx

export {A} from 'A'

so, the B.tsx includes A.tsx:

// B.tsx


include {A} from '../A'

// ...usage

now, I want to cover B by UT. I use jest for it.

So, throughout testing, I want to mock A module. I can do it using several ways:

  1. Redefine directly in the test file:
//test.tsx


jest.mock('../A', () => ({
  A: () => <div id='A' />
}))

That's works!

  1. Create a mock file inside __mocks__ folder

So, I have to create a __mocks__ folder at the same level as A folder and create A.tsx file inside.

__mocks__/
A/
B/

and include that mock inside the test:

// test.tsx


jest.mock('../A')

So, that approach does not work. And, seems, it does not work due to module resolution, because if I include A module directly, like:

// B.tsx

import {A} from '../A/A'

and move mock-file A.tsx to A/__mocks__/A.tsx

and change mocking:

// test.tsx


jest.mock('../A/A')

then, everything works properly.

So, the task is to fix module resolution somehow.

Upvotes: 0

Views: 274

Answers (1)

Brian Adams
Brian Adams

Reputation: 45810

Node tries to resolve this module:

../A

...and detects that it is a folder that doesn't have a package.json so it loads index.js.

This means that this line:

../A

...can also be written like this:

../A/index

So to create a Manual Mock you should create your mock here:

../A/__mocks__/index.ts

...and that mock will be used when you call this in your test:

jest.mock('../A');  // <= uses the mock at ../A/__mocks__/index.ts

Upvotes: 1

Related Questions