jest.fn在调用时返回undefined [英] jest.fn returns undefined when called

查看:396
本文介绍了jest.fn在调用时返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在测试中实现提取模拟功能.在以下教程中,我试图通过使用jest.fn()来做到这一点:

I am trying to implement a fetch mock function in my test. Following tutorials I am trying to do this by using jest.fn():

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

由于某些原因,此方法不起作用. 如果我只是在测试中做console.log(fetchFunction),我会得到:

This does not work for some reason. If I just do console.log(fetchFunction) in my test I get:

[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吗?

However if I try to invoke it by console.log(fetchFunction()) I get undefined?

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

I am trying this to do in a create-react-app folder. Do I have to install something extra? Any ideas about why this happens?

推荐答案

验证以下各项是否按预期工作:

Validated that the following works as expected:

test('Some test...', () => {
  const fetchFunction = jest.fn(() => null)

  console.log(fetchFunction());
});

使用Jest 24.9.0.

Using 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

这篇关于jest.fn在调用时返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆