简体   繁体   中英

How to mock functions of a function?

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM