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

feat: add Scope#clone() method #2564

Merged
merged 2 commits into from
Jan 14, 2024
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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1066,6 +1066,17 @@ if (!nock.isActive()) {
}
```

### .clone()

You can clone a scope by calling `.clone()` on it:

```js
const scope = nock('http://example.test')

const getScope = scope.get('/').reply(200)
const postScope = scope.clone().post('/').reply(200)
```

## Restoring

You can restore the HTTP interceptor to the normal unmocked behaviour by calling:
Expand Down
4 changes: 4 additions & 0 deletions lib/scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,10 @@ class Scope extends EventEmitter {
this.date = d || new Date()
return this
}

clone() {
return new Scope(this.basePath, this.scopeOptions)
}
}

function loadDefs(path) {
Expand Down
23 changes: 23 additions & 0 deletions tests/got/test_scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -217,4 +217,27 @@ describe('filteringRequestBody()', () => {
'Invalid arguments: filtering request body should be a function or a regular expression',
)
})

describe('`Scope#clone()`', async () => {
it('creates a new Scope with the same basePath and scope options', () => {
const scope = nock('http://example.test', { encodedQueryParams: true })
const clonedScope = scope.clone()

expect(clonedScope.basePath).to.equal(scope.basePath)
expect(clonedScope.scopeOptions).to.deep.equal(scope.scopeOptions)
})

it('creates a new Scope that works independently', async () => {
const scope = nock('http://example.test')

const getScope = scope.get('/').reply(200)
const postScope = scope.clone().post('/').reply(200)

await got('http://example.test/')
expect(getScope.isDone()).to.be.true()

await got.post('http://example.test/')
expect(postScope.isDone()).to.be.true()
})
})
})