jest.fn 调用时返回未定义

Sir*_*oob 4 func reactjs jestjs

我正在尝试在测试中实现 fetch 模拟函数。按照教程,我尝试使用以下方法来做到这一点jest.fn()

const fetchFunction = jest.fn(() => {
    return null
})
Run Code Online (Sandbox Code Playgroud)

由于某种原因,这不起作用。如果我只是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]
      }
Run Code Online (Sandbox Code Playgroud)

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

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

Tob*_*bbe 10

这是因为 Create-React-AppresetMocks默认处于打开状态。要关闭它,您可以将其放入 package.json 中

"jest": {
  "resetMocks": false
}
Run Code Online (Sandbox Code Playgroud)

他们在 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