简体   繁体   English

使用Jest模拟请求标头模块

[英]Mocking Request Header module using Jest

function createRequest(method) {
     const init = {
         method,
         headers: new Headers({.....}),
     };

    return new Request(url, init); }

I am using Request headers (with Fetch) in the above code ( https://davidwalsh.name/fetch ) 我在上面的代码中使用Request头(带Fetch)( https://davidwalsh.name/fetch

However while writing unit test cases using Jest, it gives me this error: ReferenceError: Headers is not defined 但是,在使用Jest编写单元测试用例时,它会给出以下错误:ReferenceError:未定义标头

DO I need to mock even these standard modules? 我是否需要模拟这些标准模块? How should I import Headers in unit test cases 如何在单元测试用例中导入Headers

I say yes, mocking Headers is definitely an option in a testing context. 我说是的,嘲笑Headers肯定是测试环境中的一个选项。 In my particular case, I have simply mocked it like so: 在我的特殊情况下,我简单地嘲笑它:

global.Headers = ()=>{}

This will work just fine if you want to test that your code is behaving properly based on the response returned by fetch. 如果您想根据fetch返回的响应测试代码是否正常运行,这将正常工作。 If you also need to check that the correct headers are sent, you would need a more sophisticated mock, and/or perhaps a specialized test suite for your networking methods. 如果您还需要检查是否发送了正确的标头,则需要更复杂的模拟,和/或可能需要专门的网络方法测试套件。

I know this is an old question, but for anyone who runs into this (as I did), this worked for me: 我知道这是一个古老的问题,但对于任何碰到这个问题的人(正如我所做的那样),这对我有用:

// before running each test
beforeEach(() => {
  // define `append` as a mocked fn
  const append = jest.fn();
  // set test `Headers`
  global.Headers = () => ({
    append: append,
  });
});

将'import“isomorphic-fetch”'添加到jest安装文件应解决此问题,因为这将使测试中缺少的dom API可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM