1

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);
  }
}

Codesandbox Example

4

1 回答 1

0

你没有axios-mock-adapter正确使用,这里是mock.onGet()方法的签名"axios-mock-adapter": "^1.19.0"

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`)];
});
于 2020-12-22T04:33:38.377 回答