Search code examples
node.jsnock

Creating dynamic mock request using npm-nock


I'm having issues mocking a dynamic url using nock

Url I want to mock:
http://example.api.com/svc/Utility.svc/json/GetAPICallRefresh_Module?from=2017-11-25T12:20:50.404Z&module=tennis&languageCode=2

Problem is the from parameter which is an ISO timestamp and changing for each API call.

Mock request:

nock('http://example.api.com')
    .persist()
    .filteringPath(/from=[^&]*/g, 'module=tennis', 'languageCode=2')
    .get('/svc/Utility.svc/json/GetAPICallRefresh_Module?module=tennis&languageCode=2')
    .reply(200, () => {
        return 'Mock response!'
    });

Not working: Error: Nock: No match for request Can you help out?


Solution

  • get should only contain your path however you have your query string included.

    Query string can be matched using the query function.

    Try this:

    nock('http://example.api.com')
      .get('/svc/Utility.svc/json/GetAPICallRefresh_Module')
      .query({ module: 'tennis', languageCode: '2' })
      .reply(200, { return 'Mock response!' });