如何模拟函数的功能?
How to mock functions of a function?
我在我的脚本中使用 simple-git
是这样的:
import simpleGit from 'simple-git'
const git = simpleGit()
const foo = async (): Promise<void> => {
const tags: string = await git.tag({
'--list': null,
'--format': '%(objectname:short)'
})
}
在我的测试中,我需要模拟 git 调用,我正在这样做:
jest.mock('simple-git', () => ({
tag: () => jest.fn()
}))
但是这是失败的。我想,我必须照顾 const git = simpleGit()
如果 simple-git
是通过 node_module
安装的(我假设是这样),您只需在项目的根目录下创建一个名为 __mocks__
的目录,任何放置在那里的内容都会自动在你的情况下嘲笑你需要创建一个名为 simple-git.js
的文件
.
├── __mocks__
│ └── simple-git.js
├── node_modules
我在我的脚本中使用 simple-git
是这样的:
import simpleGit from 'simple-git'
const git = simpleGit()
const foo = async (): Promise<void> => {
const tags: string = await git.tag({
'--list': null,
'--format': '%(objectname:short)'
})
}
在我的测试中,我需要模拟 git 调用,我正在这样做:
jest.mock('simple-git', () => ({
tag: () => jest.fn()
}))
但是这是失败的。我想,我必须照顾 const git = simpleGit()
如果 simple-git
是通过 node_module
安装的(我假设是这样),您只需在项目的根目录下创建一个名为 __mocks__
的目录,任何放置在那里的内容都会自动在你的情况下嘲笑你需要创建一个名为 simple-git.js
.
├── __mocks__
│ └── simple-git.js
├── node_modules