使用正则表达式诺克 "no match for request"

Nock "no match for request" with regex

我在使用 nock 从我的 Node.js 代码模拟 HTTP 请求时遇到问题。
为了发出请求,我正在使用 axios 库:

axios.get(`https://api.spoonacular.com/recipes/${id}/information?apiKey=${process.env.MY_SPOONACULAR_KEY}`);

id 只是一个整数,如 1131030.

我是这样使用箭尾的:

nock('https://api.spoonacular.com')
    .persist()
    .log(console.log)
    .get('/recipes\/\d*\/information$/')
    .query(true)
    .reply(200, {answer: 'any'});

我正在使用 query(true) 来匹配任何查询字符串。 get 中的正则表达式匹配请求中任何可能的 ID。

但是它不起作用,从箭尾日志中我得到以下信息:

matching https://api.spoonacular.com:443/recipes/1131030/information to GET https://api.spoonacular.com:443/recipes/d*/information$/: false

您正在向 .get() 方法传递字符串,而不是正则表达式。您需要删除引号。

.get(/recipes\/\d*\/information$/)

此外,在尝试找出 Nock 不匹配的原因时,使用 .log() 并不是首选。使用 DEBUG 来获取更多信息。 https://github.com/nock/nock#debugging