node.js - 带有 fetch-mock 的 Jest 生成错误 : TypeError: Cannot read property 'prototype' of undefined when using on nodejs

标签 node.js jestjs

我几乎可以肯定这是我的错误,但我花了一整天的时间试图解决,但失败了😞。

我正在尝试配置 Node 上的 fetch-mock 以与 jest 一起使用。我尝试了很多事情,最好的结果是这样的:

https://user-images.githubusercontent.com/824198/50566568-7b49e400-0d22-11e9-884f-89720899de3a.png

我确信我的模拟正在工作,因为如果我将它通过参数传递给“Myclass.query”,它就会完美地工作。

我还确信模拟已到达我的测试文件中,因为模拟函数存在于获取模块中。

但是...所有这些都行不通。

我创建了一个非常简单的小项目来观察这个问题的发生:

https://github.com/cesarjr/test-node-fetch

有人可以帮助我吗?

最佳答案

Jest 在测试过程中需要 node-fetch 时随时使用 __mocks__/node-fetch.js 处的模拟。

问题是 the first thing fetch-mock does is require node-fetch .

这意味着在 config 上设置 Request 时未定义 here ,因此在未定义的 Request 上调用 prototype 会导致错误 here .

比我聪明的人可能知道如何在 fetch-mock 需要 node 时强制 Jest 需要实际的 node-fetch -fetchnode-fetch 的模拟中,但从我所看到的来看,它看起来不太可能。

<小时/>

看起来您必须删除 __mocks__/node-fetch.js 处的模拟并将 fetch 传递给您的代码,如下所示:

myclass.js

class MyClass {
  static query(fetch, sessionId, query) {
    const url = 'https://api.foobar.com';

    const body = {
      sessionId,
      query
    };

    return fetch(url, {
      method: 'post',
      body: JSON.stringify(body)
    })
      .then(res => res.json());
  }
}

module.exports = MyClass;

...然后在测试中创建沙箱并将其传递给您的代码,如下所示:

myclass.test.js

const fetch = require('fetch-mock').sandbox();
const MyClass = require('./myclass');

describe('MyClass', () => {
  describe('.query', () => {
    it('returns the response', () => {
      fetch.mock('*', {'result': {'fulfillment': {'speech': 'The answer'}}});

      expect.assertions(1);

      return MyClass.query(fetch, '123', 'the question').then((data) => {
        expect(data.result.fulfillment.speech).toBe('The answer');  // SUCCESS
      });
    });
  });
});

关于node.js - 带有 fetch-mock 的 Jest 生成错误 : TypeError: Cannot read property 'prototype' of undefined when using on nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000152/

相关文章:

javascript - 上传图片到s3 bucket node js

javascript - 无法在 ubuntu 20.04 上安装 BrainJS

node.js - 装饰器中不支持'Injectable'函数调用的模板编译过程中的错误,但已调用'ɵmakeDecorator'

javascript - Selenium - 单击按钮直到出现某些元素

reactjs - package.json 中的 Jest 配置失败

javascript - 如何使用 Zod 的 isEmail?

javascript - 在 Jest 中调试单个测试

javascript - 类型错误 : Expected throat size to be a number but got undefined

typescript - 为每个测试创建一个单独的(在内存中)数据库

javascript - Stryker 和 Jest 的麻烦