Search code examples
nock

How do I do a Regex path match for a POST request with Nock.js?


I am trying to chain some requests in Nock with Regex matching on the path. All of the examples I see of Regex path matching are get requests. How do I do this properly? Is the below right?

nock('https://base-url.com')
            .post('/v1/secrets/*$', {
                username: 'pgte',
                email: '[email protected]',
            })
            .reply(200)

Solution

  • The following code demonstrates a successful Nock on a POST request using a regex on the path.

    nock('https://base-url.com')
      .post(/^\/v1\/secrets\/.*$/, {
        username: 'pgte',
        email: '[email protected]',
      })
      .reply(200, 'OK')
    
    const resp = await axios.post('https://base-url.com/v1/secrets/foobar', {
      username: 'pgte',
      email: '[email protected]',
    })
    
    expect(resp.status).toBe(200)
    expect(resp.data).toBe('OK')
    

    Things to note about the value passed to the post method; If you want to use regex matching, you need to pass an instance of a RegExp as the first argument. Here I'm using the short-hand notation, but you could also create an instance using the new RegExp("...") notation, if desired.

    Also, the example in your question had the asterisk character directly after the last slash. Which translates to the path needs to end with zero or more slashes. I assume that's not what you want, but my point is, use something like https://regex101.com to validate your regexs.

    Nock will test the pathname of the URL (as defined here) against the regex, including the leading slash.