Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nock.js - how to match any parameter combination in a URL

I am trying to simulate the response to this API URL

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

The URL parameter combinations can 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 my test case runs:

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

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

like image 629
rubayeet Avatar asked Jan 08 '15 16:01

rubayeet


People also ask

How do I pass a URL with multiple parameters into a URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

How do you handle a parameter in a URL?

Also known by the aliases of query strings or URL variables, parameters are the portion of a URL that follows a question mark. They are comprised of a key and a value pair, separated by an equal sign. Multiple parameters can be added to a single page by using an ampersand.

Can you use Javascript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.


2 Answers

With nock you can 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 passed query string:

nock('http://api.myapihost.com')
  .get('/images')
  .query(true)
  .reply(200, {});
like image 86
Benny Neugebauer Avatar answered Sep 25 '22 15:09

Benny Neugebauer


You should use path filtering in order to match the URL parameters.

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

You could check the docs here

like image 43
ELavicount Avatar answered Sep 25 '22 15:09

ELavicount