在自述中,它解释了how one can ignore the request body。
我正在使用nock的固定装置功能,我需要(至少部分地)忽略请求正文。我怎样才能做到这一点?我可以在灯具文件中json条目的body
字段中写一个正则表达式吗?
答案 0 :(得分:0)
经过一些痛苦的挖掘,我自己解决了这个问题。解决方法如下:
我正在尝试取消对Kraken API的请求。对端点/0/private/TradesHistory
的请求是方法POST
的请求,并发送包含“类似于查询字符串”字符串的body
。例如,主体将看起来像ofs=50&nonce=xxx
。 nonce
的值随每个请求而变化,因此在查找匹配的nock时我想忽略它。 (随机数只能使用一次,客户端库再次发送相同的值是没有意义的。)
因此,我必须像对nockBack
的调用中添加“预处理”函数作为配置对象,如下所示:
import * as queryString from 'query-string'
import { back } from 'nock'
import * as path from 'path'
const before = (scope: any) => {
scope.filteringRequestBody = (body: string, aRecordedBody: string) => {
const { of: currentOffset, } = queryString.parse(`?${body}`) //Prepend a `?` so it is actually a query string.
const { of: recordedOffset, } = queryString.parse(`?${body}`)
if (!(currentOffset || recordedOffset)) {//This is the case where no offset is set. There is only possible recorded body in my case that matches this: The other body which has no offset. I replace the body with the recorded body to produce a match.
return aRecordedBody
}
if (currentOffset === recordedOffset) {//This is the case where the sent body has the same offset as the recorded body. I replace the body with the recorded body in order to produce a match.
return aRecordedBody
}
return body
}
}
back.fixtures = `${__dirname}/nockFixtures/`
const { nockDone } = back('nocks.json',{before})
...//Run my queris
nockDone()
现在,它就像一种魅力。