【发布时间】:2018-04-25 11:59:30
【问题描述】:
我正在使用诺克。 我想知道我是否只能模拟对主机的一些调用,具体取决于路径。我正在使用 {allowUnmocked: true },它没有帮助。
例如,我只想模拟这些调用中的一个(数字是 id,所以我不知道全部):
这个问题和这个问题类似: Mocking with Nock, mock only a specific route with the same host
【问题讨论】:
我正在使用诺克。 我想知道我是否只能模拟对主机的一些调用,具体取决于路径。我正在使用 {allowUnmocked: true },它没有帮助。
例如,我只想模拟这些调用中的一个(数字是 id,所以我不知道全部):
这个问题和这个问题类似: Mocking with Nock, mock only a specific route with the same host
【问题讨论】:
诺克拦截器only fire once
你可以配置一个包罗万象的路径,像这样:
nock('http://blabla.com').get(/account/) // if any path has 'account' in it, somewhere
一旦该拦截器被捕获,nock 将不会捕获对该匹配 URL 的下一次调用。
或者你可以指定一个特定的 ID,比如
nock('http://blabla.com').get('/account/' + id)
显然只有那个 ID 会被拦截,因为其他 ID 不会匹配模式。您也可以为每个回复做出不同的模拟回复。
【讨论】:
这就是我所做的。我想模拟所有在他们的路径中有 123456 的呼叫。所以,如果路径没有它,我返回 X,并且只获取那些不是 X 的(使用负前瞻正则表达式)
nock(`https://my-url.com`, {
allowUnmocked: true,
})
.filteringPath((thePath) => {
const match = /123456/.test(thePath);
return match ? thePath : 'X';
})
.persist()
// This handles all request but 'X' (returned by the filteringPath fn).
.get(/^(?!(?:X)$).*$/)
【讨论】: