【问题标题】:jest.fn returns undefined when calledjest.fn 调用时返回 undefined
【发布时间】:2020-12-01 14:24:57
【问题描述】:

我正在尝试在我的测试中实现一个 fetch 模拟函数。按照教程,我正在尝试使用jest.fn()

const fetchFunction = jest.fn(() => {
    return null
})

由于某种原因,这不起作用。 如果我在测试中只做console.log(fetchFunction),我会得到:

[Function: mockConstructor] {
        _isMockFunction: true,
        getMockImplementation: [Function],
        mock: [Getter/Setter],
        mockClear: [Function],
        mockReset: [Function],
        mockRestore: [Function],
        mockReturnValueOnce: [Function],
        mockResolvedValueOnce: [Function],
        mockRejectedValueOnce: [Function],
        mockReturnValue: [Function],
        mockResolvedValue: [Function],
        mockRejectedValue: [Function],
        mockImplementationOnce: [Function],
        mockImplementation: [Function],
        mockReturnThis: [Function],
        mockName: [Function],
        getMockName: [Function]
      }

但是,如果我尝试通过console.log(fetchFunction()) 调用它,我会得到undefined

我正在尝试在 create-react-app 文件夹中执行此操作。我必须安装一些额外的东西吗?关于为什么会发生这种情况的任何想法?

【问题讨论】:

    标签: reactjs jestjs func


    【解决方案1】:

    这是因为 Create-React-App 默认开启了resetMocks。要关闭它,你可以把它放在你的 package.json 中

    "jest": {
      "resetMocks": false
    }
    

    他们在 4.0 版本中对此进行了更改。他们确实在他们的更新日志https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md#400-2020-10-23 中提到了这一点,但我猜我并不是唯一一个错过/不知道这一点的人......

    关于恢复该更改有一个未解决的问题:https://github.com/facebook/create-react-app/issues/9935

    【讨论】:

      【解决方案2】:

      验证以下内容按预期工作:

      test('Some test...', () => {
        const fetchFunction = jest.fn(() => null)
      
        console.log(fetchFunction());
      });
      

      使用 Jest 24.9.0。

       PASS  ./test.js
        ✓ foo (31ms)
      
        console.log test.js:6
          null
      
      Test Suites: 1 passed, 1 total
      Tests:       1 passed, 1 total
      Snapshots:   0 total
      Time:        7.677s
      Ran all test suites
      

      【讨论】:

      • 是的,但如果我在 test() 之外定义 fetchFunction ,它不会!我需要在 test 之外定义我的 jest.fn 函数,因为我想用一个模拟函数覆盖 global.fetch 并且它也返回 undefined,即使我在许多教程中看到它已经完成......
      • 不确定 - 我只是将函数的定义移到第 1 行,它也可以正常工作。这是回复:repl.it/@xurion/scoped-jest-mocks
      【解决方案3】:

      如果您的笑话的 resetMocks 配置属性设置为 true,您应该期望根据文档的行为:

      在每次测试前自动重置模拟状态。相当于 在每次测试之前调用 jest.resetAllMocks() 。这将导致任何 删除了假实现但不恢复的模拟 他们的初始实施。

      https://jestjs.io/docs/configuration#resetmocks-boolean

      resetMocks 设置为true,我通过在测试本身中定义我的模拟函数实现来解决它:

      it('your test' ()=> {
        //define your mock implementation here
      })
      

      【讨论】:

        猜你喜欢
        • 2021-12-20
        • 2021-11-18
        • 2018-07-29
        • 1970-01-01
        • 1970-01-01
        • 2021-11-04
        • 2018-04-02
        • 2021-09-16
        • 1970-01-01
        相关资源
        最近更新 更多