【问题标题】:jest js manual mocking chained methodsjest js 手动模拟链式方法
【发布时间】:2021-06-01 21:07:00
【问题描述】:

我想用 jest 手动模拟 npm 模块 unirest。我创建了一个__mocks__ 并将 unirest.js 放在那里。我已经创建了 post 方法和 headers 方法,但我不断收到此错误。我如何创建这些链式方法并获得响应。

TypeError: unirest.post(...).headers 不是函数

unirest
  .post('http://mockbin.com/request')
  .headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
  .send({ "parameter": 23, "foo": "bar" })
  .then((response) => {
    console.log(response.body)
  })

这是我__mocks__/unirest.js中的代码

const unirest = jest.genMockFromModule('unirest');

const result = {
    data: 'theresponse'
};

const myheaders = {'Accept': 'application/json', 'Content-Type': 'application/json'};

function headers(header) {
    header = myheaders;
    return header; 
}
console.log('inside uniREst promise mocker');

const post = opts => new Promise((resolve, reject) => {
    return resolve(result); 
  });

  

unirest.post = post;
unirest.headers = headers


module.exports = unirest;

【问题讨论】:

    标签: node.js npm jestjs unirest


    【解决方案1】:

    有两种选择:

    • 模拟测试的每个方法:这意味着,调用的第一个方法应该返回一个对象,其中包含第二个的假定义,返回第三个的定义,依此类推..

    • 使用带有代理的模拟对象!

    让我们看看第一种方法:你会做这样的事情......

    const FOO = 'something useful for your tests'
    const send = jest.fn().mockResolvedValue({ body: FOO })
    const headers = jest.fn().mockReturnValue({ send })
    const post = jest.fn().mockReturnValue({ headers })
    jest.unirest = post
    

    基本上,它是一个函数链:post 返回一个带有函数headers 的对象,该函数返回一个带有解析的函数send 的对象(不返回 - 解析 => 意味着一个承诺将返回一个值)到具有属性主体的对象,它将解析为您想要的任何内容。也许您想自定义每个测试。希望它可以作为一般指导方针

    Proxies 允许您在调用未定义的内容时执行get 方法。这将允许您链接任何您想要的方法,并且对于特定的 send 返回一些有用的东西.. 它会是这样的:

    const handler = {
      get: (obj) => {
        return obj
      } 
    }
    
    const send = jest.fn().mockResolvedValue({ body: FOO })
    const target = { send } 
    module.exports = new Proxy(target, handler)
    

    基本上,每当您调用 unitest 时,它都会尝试在 target 中执行该操作。如果存在,它将运行代码。否则,它会调用代理中的get函数,该函数基本上会返回对自身的引用(参数obj)。我没有使用过这种方法,但我相信它会起作用——你基本上模拟了target 中你关心的函数,其余的,你只是“什么都不做”。如果链接过多并且您不想对所有中间函数进行任何断言,这可能很有用。

    希望它能提供一些方向。

    【讨论】:

      【解决方案2】:

      const Foo = {body: 'My response from API'};
      
      function end(response) { 
          return response(Foo);
      }
           
      const send = req => {
          return { end };
      }
      
      const headers = opt => {
          return { send };
      };
      
      const post = url => {
          return { headers };
      };
      
      console.log('Calling mock unirest');
      
      module.exports = {
          post: post,
          headers: headers, 
          send: send, 
          end: end
      }

      使用下面的代码终于让它工作了。感谢 Gonzalo 的帮助

      【讨论】:

        猜你喜欢
        • 2019-06-09
        • 2017-05-23
        • 2020-01-27
        • 2018-09-16
        • 2021-12-08
        • 2019-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多