首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jest with fetch-mock生成错误: TypeError:在nodejs上使用时无法读取未定义的属性'prototype‘

Jest with fetch-mock生成错误: TypeError:在nodejs上使用时无法读取未定义的属性'prototype‘
EN

Stack Overflow用户
提问于 2019-01-02 08:57:19
回答 2查看 2.1K关注 0票数 3

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

我正在尝试将node上的fetch-mock配置为与jest一起使用。我尝试了很多方法,我得到的最好的结果是:

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

我确信我的模拟是有效的,因为如果我将它通过参数传递给"Myclass.query“,它就能完美地工作。

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

但是..。所有这些都不起作用。

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

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

有谁可以帮我?

EN

回答 2

Stack Overflow用户

发布于 2019-01-04 04:02:08

在测试过程中,只要需要node-fetchJest就会在__mocks__/node-fetch.js中使用模拟。

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

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

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

看起来你将不得不删除__mocks__/node-fetch.js中的模拟,并将fetch传递给你的代码,如下所示:

myclass.js

代码语言:javascript
复制
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;

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

myclass.test.js

代码语言:javascript
复制
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
      });
    });
  });
});
票数 1
EN

Stack Overflow用户

发布于 2019-01-20 00:25:41

我现在已经找到了一种可靠的方法来组合fetch-mock和jest http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54000152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档