带有 fetch-mock 的玩笑生成错误:TypeError: 在 NodeJS 上使用时无法读取未定义的属性“原型”

2024-02-10

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

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

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

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

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

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

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

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

谁能帮我?


Jest使用模拟__mocks__/node-fetch.js任何时候node-fetch测试期间需要。

问题是第一件事fetch-mock确实需要node-fetch https://github.com/wheresrhys/fetch-mock/blob/f4c828d78614bb0ae0e7f2e1e2de68623bd3d67b/src/server.js#L1.

这意味着Request设置时未定义config here https://github.com/wheresrhys/fetch-mock/blob/f4c828d78614bb0ae0e7f2e1e2de68623bd3d67b/src/server.js#L15,所以调用prototype关于未定义的Request导致错误here https://github.com/wheresrhys/fetch-mock/blob/f4c828d78614bb0ae0e7f2e1e2de68623bd3d67b/src/lib/request-utils.js#L38.

比我聪明的人可能知道如何强迫Jest来要求实际的node-fetch when fetch-mock需要node-fetch在模拟中node-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;

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

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
      });
    });
  });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有 fetch-mock 的玩笑生成错误:TypeError: 在 NodeJS 上使用时无法读取未定义的属性“原型” 的相关文章

随机推荐