Nock.js - how to match any combination of parameters in a url

I am trying to simulate a response to this API url

http://api.myapihost.com/images?foo=bar&spam=egg 

Combinations of URL parameters may vary. I am trying to intercept this request and respond with an empty object.

 nock('http://api.myapihost.com') .persist() .get('/images', '*') .reply(200, {}); 

I get this error message when a test script runs:

 Uncaught Error: Nock: No match for HTTP request GET /images?height=2500 

How to configure nock to match any combination of URL parameters?

+5
source share
2 answers

You must use path filtering to match the URL parameters.

 var scope = nock('http://api.myapihost.com') .filteringPath(function(path) { return '/images'; }) .get('/images') .reply(200, {}); 

You can check the documents here

+2
source

With nock, you can also specify regular expressions .

Here is an example (tested with v9.2.3):

 nock('http://api.myapihost.com') .get(/images.*$/) .reply(200, {}); 

There is also a simpler syntax using .query(true) if you want to mock the entire URL regardless of the query string passed:

 nock('http://api.myapihost.com') .get('/images') .query(true) .reply(200, {}); 
+2
source

Source: https://habr.com/ru/post/1210678/


All Articles