简体   繁体   中英

Axios Mock Adapter with repeated params

I am am using a mock adapter for my tests in a react app, and one of them looks like this:

http://endpoint.com/api/entities?id=123&select=labels&select=versions&labelsLang=en

The important part to note is that the select parameter is in there twice.

One of the tests is rendering in another language, so we have two mock endpoints set up to reflect this, however I cannot seem to find a way to properly mock the repeated paramter. I just keep on getting a result for the first one.

The code for the mocked endpoints is this:

const mockApiClient = axios.create({ baseURL: "http://localhost" });
const mock = new MockAdapter(mockApiClient);

const params1 = new URLSearchParams();
params1.append("id", "123");
params1.append("select", "labels");
params1.append("select", "versions");
params1.set("labelsLang", "en");
mock
  .onGet("/entities", {
    asymmetricMatch: function(actual: any) {
      return actual.params.toString() === params1.toString();
    },
  })
  .reply(200, getCompanyResponse);

const params2 = new URLSearchParams();
params2.append("id", "123");
params2.append("select", "labels");
params2.append("select", "versions");
params2.set("labelsLang", "de");
mock
  .onGet("/entities", {
    asymmetricMatch: function(actual: any) {
      return actual.params.toString() === params2.toString();
    },
  })
  .reply(200, getCompanyResponseDE);

I know it's messy, I just want to understand how to do this properly.

Whenever I try specifying specific params in an object, it complains that you cant have a duplicate key .

(ie. { params:{select:'labels', select:'versions} } )

Solved.

Here's how it was done:

const mockApiClient = axios.create({ baseURL: "http://localhost" });
const mock = new MockAdapter(mockApiClient);

const params1 = {
  "id": "123",
  select: ["labels", "versions"],
  "labelsLang": "en",
};
mock
  .onGet("/entities", {
    params: {
      asymmetricMatch: function(actual: any) {
        actual.sort(); // Important, as without it the order of params would affect the result
        return actual.toString() === toURLSearchParams(params1).toString();
      },
    },
  })
  .reply(200, getCompanyResponse);


export const toURLSearchParams = (params: {[key: string]: string|string[]}, sort:boolean = true):URLSearchParams => {
  if(params instanceof URLSearchParams) return params

  const searchParams = new URLSearchParams();
  for(const key in params){
    const value = params[key];
    if(Array.isArray(value)){
      value.forEach((eachValue) => {
        searchParams.append(key, eachValue)
      })
    } else {
      searchParams.append(key,value)
    }
  }
  if(sort) searchParams.sort() // Likewise here. 
  return searchParams;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM