node.js - 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;
解决方案
有两种选择:
模拟测试的每个方法:这意味着,调用的第一个方法应该返回一个对象,其中包含第二个的假定义,返回第三个的定义,依此类推..
使用带有代理的模拟对象!
让我们看看第一种方法:你会做这样的事情......
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
,而对于其余的,你只是“什么都不做”。如果有太多链接并且您不想对所有中间函数进行任何断言,这可能很有用。
希望它提供一些方向。
推荐阅读
- html - 正文结束后如何设置背景颜色?
- r - 如何创建一个填充数据集中两个变量之间相关性的热图函数?
- android - 从在 Docker 中运行的 Android 模拟器连接到 Redis
- mysql - 存储第三方应用程序的凭据
- android - 我应该相信谷歌应用程序崩溃报告,因为同样的事情在真实设备上工作
- mysql - 如何将 MySQL 5.7 升级到 MySQL 8.4
- stripe-payments - 当同一张信用卡附加到另一个客户对象时,Stripe 是否会重新运行 $0/$1 授权?
- laravel - Laravel 使用 Supervisor 排队 - 进入 FATAL 状态,启动重试次数过多太快
- android - 安卓软件与互联网网络中的ESP8266实时通信
- ruby - 在 Windows 上安装 gem http_parser