【问题标题】:How to mock functions of a function?如何模拟函数的函数?
【发布时间】:2021-10-15 20:46:30
【问题描述】:

我在我的脚本中使用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()

【问题讨论】:

  • mockImplementation 参数是一个返回测试替身的工厂函数。您正在尝试替换一个函数,工厂提供了一个对象。所以我猜当你说“失败”(在minimal reproducible example 中包含输出)时,你被告知它是不可调用的。

标签: javascript unit-testing testing jestjs


【解决方案1】:

如果simple-git 是通过node_module 安装的(我假设是这样),您只需要在项目的根目录下创建一个名为__mocks__ 的目录,在您需要创建的情况下,放置在那里的任何内容都会自动模拟一个名为simple-git.js的文件

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

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

【讨论】:

    猜你喜欢
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多