首页 > 解决方案 > jest js 手动模拟链式方法

问题描述

我想用 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.jsnpmjestjsunirest

解决方案


有两种选择:

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

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

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

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 返回一个带有 function 的对象,该headers函数返回一个带有一个函数的对象,该函数send解析(不返回 - resolves => 表示将返回一个值的承诺)到一个带有 a 的对象财产主体,它将解决您想要的任何问题。也许您想自定义每个测试。希望它可以作为一般指导方针

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

希望它提供一些方向。


推荐阅读