Home > Software engineering >  How to mock functions of a function?
How to mock functions of a function?

Time:10-16

I'm using simple-git in my script like this:

import simpleGit from 'simple-git'
const git = simpleGit()

const foo = async (): Promise<void> => {
  const tags: string = await git.tag({
    '--list': null,
    '--format': '%(objectname:short)'
  })
}

In my tests I need to mock out the git calls, which I'm doing this way:

jest.mock('simple-git', () => ({
  tag: () => jest.fn()
}))

But this is failing. I guess, I have to take care of const git = simpleGit()

CodePudding user response:

If simple-git is installed via node_module (which I assume it is) you only need to create a directory called __mocks__ at the root of your project anything placed there is automatically mocked in your case you need to create a file called simple-git.js

.
├── __mocks__
│   └── simple-git.js
├── node_modules

Reference: https://jestjs.io/docs/manual-mocks#mocking-node-modules

  • Related