When trying to setup axios to mock requests to an incomplete api server I'm using to build a front end, I am getting 404 responses on all requests, even those that aren't mocked at all.
const api = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/"
});
const mock = new MockAdapter(api);
// setup the mock url
mock.onGet("/test", ({ url }) => {
console.log(url);
return import(`./mocks/${url}.json`);
});
async function testMock() {
try {
const shouldBeMocked = await api.get("/test");
console.log(shouldBeMocked);
} catch (err) {
console.log("this should have been mocked");
console.log(err);
}
try {
const isRealURL = await api.get("/json/1");
console.log(isRealURL);
} catch (err) {
console.log("this should have fetched from the api");
console.log(err);
}
try {
const isRealURLWithFetch = await fetch(
"https://jsonplaceholder.typicode.com/json/1"
);
const data = await isRealURLWithFetch.text();
console.log(data);
} catch (err) {
console.log("this won't be logged");
console.log(err);
}
}
You didn't use axios-mock-adapter
correctly, here is the signature of mock.onGet()
method for "axios-mock-adapter": "^1.19.0"
.
type RequestMatcherFunc = (
matcher?: string | RegExp,
body?: string | AsymmetricRequestDataMatcher,
headers?: AsymmetricHeadersMatcher
) => RequestHandler;
As you can see, the second parameter is NOT the "reply" function. You should pass the function to the reply
method.
mock.onGet("/test").reply(async ({ url }) => {
console.log(url);
return [200, await import(`./mocks/${url}.json`)];
});