所有请求的 Axios 模拟适配器 returns 404
Axios mock adapter returns 404 on all reqeusts
当尝试设置 axios 来模拟对我用来构建前端的 api 服务器的请求时,我收到了所有请求的 404 响应,即使是那些根本没有被模拟的请求.
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);
}
}
您没有正确使用 axios-mock-adapter
,这里是 "axios-mock-adapter": "^1.19.0"
的 mock.onGet()
方法的签名。
type RequestMatcherFunc = (
matcher?: string | RegExp,
body?: string | AsymmetricRequestDataMatcher,
headers?: AsymmetricHeadersMatcher
) => RequestHandler;
如您所见,第二个参数不是“回复”功能。您应该将函数传递给 reply
方法。
mock.onGet("/test").reply(async ({ url }) => {
console.log(url);
return [200, await import(`./mocks/${url}.json`)];
});
当尝试设置 axios 来模拟对我用来构建前端的 api 服务器的请求时,我收到了所有请求的 404 响应,即使是那些根本没有被模拟的请求.
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);
}
}
您没有正确使用 axios-mock-adapter
,这里是 "axios-mock-adapter": "^1.19.0"
的 mock.onGet()
方法的签名。
type RequestMatcherFunc = (
matcher?: string | RegExp,
body?: string | AsymmetricRequestDataMatcher,
headers?: AsymmetricHeadersMatcher
) => RequestHandler;
如您所见,第二个参数不是“回复”功能。您应该将函数传递给 reply
方法。
mock.onGet("/test").reply(async ({ url }) => {
console.log(url);
return [200, await import(`./mocks/${url}.json`)];
});