Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Push persisted interceptors to the end instead of ignore on remove #2350

Merged
merged 2 commits into from
Jun 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1002,7 +1002,7 @@ const scope = nock('http://example.com')
.reply(200, 'Persisting all the way')
```

Note that while a persisted scope will always intercept the requests, it is considered "done" after the first interception.
Note that while a persisted scope will always intercept the requests, it is considered "done" after the first interception, and they are pushed to the bottom of the stack after consumption.

If you want to stop persisting an individual persisted mock you can call `persist(false)`:

Expand Down
8 changes: 7 additions & 1 deletion lib/intercept.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ function addInterceptor(key, interceptor, scope, scopeOptions, host) {
}

function remove(interceptor) {
if (interceptor.__nock_scope.shouldPersist() || --interceptor.counter > 0) {
if (--interceptor.counter > 0) {
return
}

Expand All @@ -122,6 +122,12 @@ function remove(interceptor) {
// matching instance. I'm also not sure why we couldn't delete _all_
// matching instances.
interceptors.some(function (thisInterceptor, i) {
if (interceptor.__nock_scope.shouldPersist()) {
return thisInterceptor === interceptor
? interceptors.push(interceptors.splice(i, 1)[0])
: false
}

return thisInterceptor === interceptor ? interceptors.splice(i, 1) : false
})
}
Expand Down
19 changes: 19 additions & 0 deletions tests/test_persist_optionally.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,25 @@ describe('`persist()`', () => {
expect(scope.isDone()).to.be.true()
})

it('persisted mocks go to the bottom of the stack after matching', async () => {
const scope = nock('http://example.test')
.persist()
.get('/')
.reply(200, 'Persisting all the way')

const specificTestScope = nock('http://example.test')
.get('/')
.reply(201, 'return different response once')

await got('http://example.test/')

expect(scope.isDone()).to.be.true()

await got('http://example.test/')

expect(specificTestScope.isDone()).to.be.true()
})

it('persisted mocks appear in `pendingMocks()`', async () => {
const scope = nock('http://example.test')
.get('/abc')
Expand Down