ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.47k stars 245 forks source link

Add more information for onNoMatch: throwException #310

Closed fanantoxa closed 3 months ago

fanantoxa commented 3 years ago

Domain knowlage

With last update there is a way to make axios-mock-adapter to throw an error when unhanded request happen.

const mock = new MockAdapter(axios, { onNoMatch: "throwException" });

So when when I make call I see error:

axios.get("/user/posts");

// Exception message on console:
//
// Could not find mock for: 
// {
//   "method": "get",
//   "url": "http://localhost/user/posts"
// }

Problem

There case when component makes a request to the same API endpoint but with different query param. For example pagination. I can setup specific mock for so it will mock only first request but not the second For example:

const axios = require('axios')
const MockAdapter = require('axios-mock-adapter')

const mock = new MockAdapter(axios, { onNoMatch: 'throwException' })

// Mock GET request to /users when param `searchText` is 'John'
// arguments for reply are (status, data, headers)
mock.onGet('/users', { params: { searchText: 'John' } }).reply(200, {});

it('runs', async () => {
  await axios
    .get('/users', { params: { searchText: 'John' } })
    .then((response) => { console.log(response.data) })

  await axios
    .get('/users', { params: { searchText: 'Arnold' } })
    .then((response) => { console.log(response.data) })

  expect(true).toBe(true)
})

With this example I'll get error that looks like this:

Could not find mock for: 
    {
      "method": "get",
      "url": "/users"
    }

This is quite small amount of information for developer and it may take awhile to understand that the is another call to the same endpoint that mocked but with a bit different params.

Suggested solution

Add more information into the error. I'd suggest params and request body (POST, PUT, etc requests may have slight difference in body that will lead to same problem)

sarah-i-nbr commented 1 year ago

I have the same problem with POST

How did you make it work @fanantoxa ?

marcbachmann commented 3 months ago

params and headers got added in v2.0.0 body could be too big in most cases 🤔