ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mocking does not work with baseURL matching part of the URL

resetko opened this issue Β· comments

"axios": "0.21.1",
"axios-mock-adapter": "1.19.0"

Issue: Adapter can't match URL if it contains part of base URL

Example: Base URL is /app and url is /appliance mock won't match 😞

var axios = require("axios");
var MockAdapter = require("axios-mock-adapter");

const instance = axios.create({
  baseURL: "/app"
});

var mock = new MockAdapter(instance);

mock.onGet("/a_ppliance").reply(200, { foo: "bar a_ppliance" });
mock.onGet("/appliance").reply(200, { foo: "bar appliance" });

instance
  .get("/a_ppliance")
  .then((response) => console.log("/a_ppliance works", response.data))
  .catch((e) => console.log("/a_ppliance error"));

instance
  .get("/appliance")
  .then((response) => console.log("/appliance works", response.data))
  .catch((e) => console.log("/appliance error"));

above code will output

/a_ppliance works { foo: 'bar a_ppliance' }
/appliance error

Link for quick check: https://codesandbox.io/s/lucid-goodall-0qu35?file=/src/index.js

Is it a known issue with known workaround? πŸ€”

This issue originated with the axis0.21.1 release for me. Currently I'm using a workaround with patch-package with the change at src/handle_request.js:

Screenshot 2021-05-29 at 3 12 46 PM

@resetko The URL is overwritten in the below if block:

if (
config.baseURL &&
url.substr(0, config.baseURL.length) === config.baseURL
) {
url = url.slice(config.baseURL.length);
}

The above code checks if the base URL and the underlying URL match, if they do, it replaces it with just the URL and removes the base URL. Not sure why we do this.

If we comment the if clause out, the above scenario works with and without a base URL and all the tests pass (there is a comment specifying that this if clause is not tested).

Another work around is if we add the whole URL along with the base URL, your scenario works:

instance
  .get("/app/appliance")
  .then((response) => console.log("/appliance works", response.data))
  .catch((e) => console.log("/appliance error"));