0

我在配置dredd时尝试使用公共端点(例如:api.openweathermap.org/data/2.5/weather?lat=35&lon=139)而不是本地主机并运行命令来运行该工具。但我不是能够通过dredd连接到端点。它正在抛出 Error:getaddrINFO EAI_AGAIN 。但是当我尝试使用 post man 连接到端点时。我能够成功连接

4

1 回答 1

1

调用本地或远程端点没有区别。

一些远程端点有某种授权要求。

这是 Dredd 调用外部端点的示例:

dredd.yml 配置文件片段

...
blueprint: doc/api.md
# endpoint: 'http://api-srv:5000'
endpoint: https://private-da275-notes69.apiary-mock.com

如您所见,唯一的变化是 Dredd 配置文件(使用 Dredd init 创建)上的端点。

但是,正如我提到的,有时您需要通过标头或查询字符串参数提供授权。

Dreed 具有允许您在每次交易之前更改内容的钩子,例如:

您希望在执行请求之前在每个 URL 中添加 apikey 参数。这段代码可以处理。

钩子.js

// Writing Dredd Hooks In Node.js
// Ref: http://dredd.org/en/latest/hooks-nodejs.html

var hooks = require('hooks');

hooks.beforeEach(function(transaction) {
  hooks.log('before each');
  // add query parameter to each transaction here
  let paramToAdd = 'api-key=23456';
  if (transaction.fullPath.indexOf('?') > -1)
    transaction.fullPath += '&' + paramToAdd;
  else
    transaction.fullPath += '?' + paramToAdd;

  hooks.log('before each fullpath: ' + transaction.fullPath);
});

Github gist上的代码

将此挂钩文件保存在项目中的任何位置,然后运行 ​​Dredd 并传递挂钩文件。

dredd --hookfiles=./hoock.js

就是这样,执行后日志将显示请求中使用的实际 URL。

info: Configuration './dredd.yml' found, ignoring other arguments.
2018-06-25T16:57:13.243Z - info: Beginning Dredd testing...
2018-06-25T16:57:13.249Z - info: Found Hookfiles: 0=/api/scripts/dredd-hoock.js
2018-06-25T16:57:13.263Z - hook: before each
2018-06-25T16:57:13.264Z - hook: before each fullpath: /notes?api-key=23456
"/notes?api-key=23456"
2018-06-25T16:57:16.095Z - pass: GET (200) /notes duration: 2829ms
2018-06-25T16:57:16.096Z - hook: before each
2018-06-25T16:57:16.096Z - hook: before each fullpath: /notes?api-key=23456
"/notes?api-key=23456"
2018-06-25T16:57:16.788Z - pass: POST (201) /notes duration: 691ms
2018-06-25T16:57:16.788Z - hook: before each
2018-06-25T16:57:16.789Z - hook: before each fullpath: /notes/abcd1234?api-key=23456
"/notes/abcd1234?api-key=23456"
2018-06-25T16:57:17.113Z - pass: GET (200) /notes/abcd1234 duration: 323ms
2018-06-25T16:57:17.114Z - hook: before each
2018-06-25T16:57:17.114Z - hook: before each fullpath: /notes/abcd1234?api-key=23456
"/notes/abcd1234?api-key=23456"
2018-06-25T16:57:17.353Z - pass: DELETE (204) /notes/abcd1234 duration: 238ms
2018-06-25T16:57:17.354Z - hook: before each
2018-06-25T16:57:17.354Z - hook: before each fullpath: /notes/abcd1234?api-key=23456
"/notes/abcd1234?api-key=23456"
2018-06-25T16:57:17.614Z - pass: PUT (200) /notes/abcd1234 duration: 259ms
2018-06-25T16:57:17.615Z - complete: 5 passing, 0 failing, 0 errors, 0 skipped, 5 total
2018-06-25T16:57:17.616Z - complete: Tests took 4372ms
于 2018-06-25T17:19:47.457 回答