问题:
我想模拟在同一个 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/