Nock 不会拦截对第 3 方的呼叫
Nock does not intercept call to 3rd party
我正在尝试使用 SuperTest 自动化一些 REST 服务。该服务是一个 POST 调用,它在内部调用另一个第三方服务 GET 方法。我正在尝试模拟第三方服务以提高测试效率并减少测试执行时间。
我正在使用 nock 来模拟第三方服务调用。
我的初始服务电话看起来像 -
curl -X POST \
http://internal-url.com/path \
-H 'Content-Type: application/json' \
-H 'cache-control: no-cache' \
-d '{
"key1": "value1",
"key2": "value2"
}'
此服务调用类似于 -
的第三方服务
curl -X GET \
'http://3rdparty-url.com/value1' \
-H 'Content-Type: application/json' \
-H 'cache-control: no-cache' \
-H 'key2: value2'
我在 beforeTest 中使用 nock 模拟了服务,例如 -
nock('http://3rdparty-url.com')
.get('/value1')
.reply(200, 'domain matched');
当我使用 SuperTest 直接调用此第三方服务时,它返回模拟响应。但是,我的 objective 是进行 POST 调用,并使用存根拦截对第三方服务的调用,这并没有发生。我在 Java 世界中使用 WireMock 实现了类似的事情。是否可以使用诺克做到这一点?
我的测试看起来像 -
var payload = {"key1": "value1", "key2": "value2"};
describe('Test third party Service', function () {
it('should return success on POST /path service', function (done) {
supertest('http://internal-url.com')
.post('/path')
.send(payload)
.expect(200)
.expect('Content-type', /application\/json/)
.expect(function (response) {
console.log(response.body);
//test fails as third party server is not available and mock doesn't intercept
})
.end(done);
});
Nock works by monkey-patching 在当前进程的内存中从 Node 的 http 和 https 模块运行。这意味着对 Nock 的调用必须与发出请求的进程在同一进程中进行。
在您的情况下,无论 运行 为 "internal-url.com" 应用什么,都需要调用 nock。 nock 和 supertest 的一个常见约定是 运行 与测试在同一进程中的内部应用程序实例。 Supertest examples 展示如何使用像 Express 这样的框架来做到这一点。
我正在尝试使用 SuperTest 自动化一些 REST 服务。该服务是一个 POST 调用,它在内部调用另一个第三方服务 GET 方法。我正在尝试模拟第三方服务以提高测试效率并减少测试执行时间。 我正在使用 nock 来模拟第三方服务调用。
我的初始服务电话看起来像 -
curl -X POST \
http://internal-url.com/path \
-H 'Content-Type: application/json' \
-H 'cache-control: no-cache' \
-d '{
"key1": "value1",
"key2": "value2"
}'
此服务调用类似于 -
的第三方服务curl -X GET \
'http://3rdparty-url.com/value1' \
-H 'Content-Type: application/json' \
-H 'cache-control: no-cache' \
-H 'key2: value2'
我在 beforeTest 中使用 nock 模拟了服务,例如 -
nock('http://3rdparty-url.com')
.get('/value1')
.reply(200, 'domain matched');
当我使用 SuperTest 直接调用此第三方服务时,它返回模拟响应。但是,我的 objective 是进行 POST 调用,并使用存根拦截对第三方服务的调用,这并没有发生。我在 Java 世界中使用 WireMock 实现了类似的事情。是否可以使用诺克做到这一点?
我的测试看起来像 -
var payload = {"key1": "value1", "key2": "value2"};
describe('Test third party Service', function () {
it('should return success on POST /path service', function (done) {
supertest('http://internal-url.com')
.post('/path')
.send(payload)
.expect(200)
.expect('Content-type', /application\/json/)
.expect(function (response) {
console.log(response.body);
//test fails as third party server is not available and mock doesn't intercept
})
.end(done);
});
Nock works by monkey-patching 在当前进程的内存中从 Node 的 http 和 https 模块运行。这意味着对 Nock 的调用必须与发出请求的进程在同一进程中进行。
在您的情况下,无论 运行 为 "internal-url.com" 应用什么,都需要调用 nock。 nock 和 supertest 的一个常见约定是 运行 与测试在同一进程中的内部应用程序实例。 Supertest examples 展示如何使用像 Express 这样的框架来做到这一点。