node.js - 如何通过具有不同状态代码的 Nock 对同一 url 进行后续调用

标签 node.js sinon nock

问题:
我想模拟在同一个 http 调用中得到不同结果的情况。具体来说,第一次失败。
在某种程度上,这类似于 stub.onFirstCall()Sinon 功能,stub.onSecondCall()期待:
我希望如果我在第一次调用时使用 once 并在第二次调用时使用 twice 我将能够完成上述操作。

nock( some_url )
    .post( '/aaaa', bodyFn )
    .once()
    .reply( 500, resp );
nock( some_url )
    .post( '/aaaa', bodyFn )
    .twice()
    .reply( 200, resp );

最佳答案

正确的方法是简单地
调用 Nock 两次。

nock( some_url )
    .post( '/aaaa', bodyFn )
    .reply( 500, resp );
nock( some_url )
    .post( '/aaaa', bodyFn )
    .reply( 200, resp );

Nock 的工作方式是每个调用都为 some_url 注册一个拦截器。
实际上第一次调用 some_url 会清除第一个拦截器等等。

docs 所述:

When you setup an interceptor for a URL and that interceptor is used, it is removed from the interceptor list. This means that you can intercept 2 or more calls to the same URL and return different things on each of them. It also means that you must setup one interceptor for each request you are going to have, otherwise nock will throw an error because that URL was not present in the interceptor list. If you don’t want interceptors to be removed as they are used, you can use the .persist() method.

关于node.js - 如何通过具有不同状态代码的 Nock 对同一 url 进行后续调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54989431/

相关文章:

node.js - 使用 POST API 时出现多个 CORS 错误

angular - SinonJS : calledWith() with exact object

javascript - 模拟 net.Socket 进行单元测试

unit-testing - 如何在 react 组件的子组件中模拟 e.preventDefault

react-native - 是否可以在排毒端到端测试期间模拟响应

node.js - 为什么 Node.js 有增量内存使用?

javascript - 如何将 HapiJs 连接到 Swagger?

javascript - 当 url 包含单引号时,如何使用 nock 和 request-promise 测试路由?

javascript - 在 Loopback 中使用 node.js 引用模型上的属性

mocha.js - 具有相同范围和路径的不同响应与 Nock 的不同身份验证 header ,可能吗?