Skip to content

Commit

Permalink
feat: Add conditionally() (#1488)
Browse files Browse the repository at this point in the history
I am building a test framework which depends on nock and to support concurrency, I need to be able shutoff certain scopes (to prevent cross-pollination) when running tests concurrently.
  • Loading branch information
parisholley authored and paulmelnikow committed Apr 15, 2019
1 parent d6667f0 commit 24e5b47
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Expand Up @@ -757,6 +757,18 @@ const scope = nock('https://api.dropbox.com', {
.reply(200)
```

### Conditional scope filtering

You can also choose to filter out a scope based on your system environment (or any external factor). The filtering function is accepted at the `conditionally` field of the `options` argument.

This can be useful if you only want certain scopes to apply depending on how your tests are executed.

```js
const scope = nock('https://api.myservice.com', {
conditionally: () => true,
})
```

### Path filtering

You can also filter the URLs based on a function.
Expand Down
8 changes: 8 additions & 0 deletions lib/interceptor.js
Expand Up @@ -254,6 +254,14 @@ Interceptor.prototype.match = function match(options, body, hostNameOnly) {
return false
}

if (
this.scope.scopeOptions &&
this.scope.scopeOptions.conditionally &&
!this.scope.scopeOptions.conditionally()
) {
return false
}

function reqheaderContains(header) {
return _.has(options.headers, header)
}
Expand Down
31 changes: 31 additions & 0 deletions tests/test_intercept.js
Expand Up @@ -8,6 +8,7 @@ const mikealRequest = require('request')
const superagent = require('superagent')
const needle = require('needle')
const restify = require('restify-clients')
const assertRejects = require('assert-rejects')
const hyperquest = require('hyperquest')
const got = require('got')
const nock = require('..')
Expand Down Expand Up @@ -1228,6 +1229,36 @@ test('test request timeout option', t => {
})
})

test('do not match when conditionally = false but should match after trying again when = true', async t => {
t.plan(2)
let enabled = false

const scope = nock('http://example.test', {
conditionally: function() {
return enabled
},
})
.get('/')
.reply(200)

// now the scope has been used, should fail on second try
await assertRejects(
got('http://example.test/'),
Error,
'Nock: No match for request'
)
t.throws(() => scope.done(), {
message: 'Mocks not yet satisfied',
})

enabled = true

const { statusCode } = await got('http://example.test/')

t.equal(statusCode, 200)
scope.done()
})

test('get correct filtering with scope and request headers filtering', t => {
const responseText = 'OK!'
const responseHeaders = { 'Content-Type': 'text/plain' }
Expand Down

0 comments on commit 24e5b47

Please sign in to comment.