我在使用nock模拟Node.js代码中的HTTP请求时遇到问题
要提出请求,我正在使用axios库:
axios.get(`https://api.spoonacular.com/recipes/${id}/information?apiKey=${process.env.MY_SPOONACULAR_KEY}`);
id只是一个类似1131030的整数。
我以这种方式使用nock:
nock('https://api.spoonacular.com')
.persist()
.log(console.log)
.get('/recipes/d*/information$/')
.query(true)
.reply(200, {answer: 'any'});
我使用查询(true(来匹配任何查询字符串。get中的regex用于匹配请求中任何可能的id。
然而,它不起作用,从nock日志中我得到了以下信息:
匹配https://api.spoonacular.com:443/recipes/1131030/information获取https://api.spoonacular.com:443/recipes/d*/信息$/:错误
您正在向.get()
方法传递一个字符串,而不是正则表达式。您需要删除引号。
.get(/recipes/d*/information$/)
此外,在试图找出Nock不匹配的原因时,使用.log()
也不是首选。使用DEBUG来获取更多信息。https://github.com/nock/nock#debugging