如何测试 fetch 的“重定向”历史?

解读

在国内前端面试中,面试官问“如何测试 fetch 的重定向历史”并不是想听你背一段 fetch 的 API,而是想确认三件事:

  1. 你是否知道浏览器在 30x 场景下默认会自动跟随,且 fetch 不会把中间跳转 URL 暴露给业务代码;
  2. 你是否能绕过这一限制,把“重定向链”变成可观测、可断言的数据;
  3. 你是否能用 Jest 把整个过程自动化,并在本地 CI(如 GitLab-Runner、GitHub Actions 国内镜像、阿里云 Flow)里稳定跑通。

因此,答题思路必须围绕“可测试性”展开:要么在 Node 侧用可编程的 Mock Server 把重定向过程显性化,要么在浏览器侧通过 Service Worker 拦截并记录历史,最终把“跳转次数、顺序、响应码、最终 URL”全部断言出来。

知识点

  1. fetch 的 redirect 选项:follow(默认)、manual、error;只有 manual 才能阻止自动跟随,但 Response 里依旧拿不到中间 URL。
  2. Node 测试环境常用“msw@node”或“nock”做网络层 Mock;两者都能一次 mock 多个路由,从而模拟 301→302→200 的完整链条。
  3. Jest 的钩子函数 beforeAll / afterAll 用来启停 Mock Server,保证用例隔离。
  4. 断言方向:重定向次数、Location 顺序、最终 status、最终 data、请求头是否携带 cookie(SameSite 场景)。
  5. 如果项目必须在真实浏览器里校验,可借助 jest-puppeteer 或 playwright-jest,并通过 page.on('request') 收集跳转链;但国内 CI 内存普遍紧张,Node 层 Mock 是性价比最高的方案。
  6. 合规提示:测试用例里禁止把公司线上域名写死,统一使用 .test 或 .local 后缀,避免误触生产环境。

答案

下面给出国内团队落地最多的“msw@node”方案,零真实请求、零配置、可直接塞进 GitLab CI。

npm i -D msw@latest jest-environment-node

tests/redirect.test.js

/**
 * @jest-environment node
 */
import { rest } from 'msw';
import { setupServer } from 'msw/node';

// 构造 3 次跳转:/a → /b → /c → 200
const server = setupServer(
  rest.get('http://my.test/a', (req, res, ctx) =>
    res(ctx.status(301), ctx.set('Location', 'http://my.test/b'))
  ),
  rest.get('http://my.test/b', (req, res, ctx) =>
    res(ctx.status(302), ctx.set('Location', 'http://my.test/c'))
  ),
  rest.get('http://my.test/c', (req, res, ctx) =>
    res(ctx.status(307), ctx.set('Location', 'http://my.test/end'))
  ),
  rest.get('http://my.test/end', (req, res, ctx) =>
    res(ctx.json({ result: 'ok' }))
  )
);

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterAll(() => server.close());
afterEach(() => server.resetHandlers());

test('应该经历 3 次重定向并拿到最终结果', async () => {
  const fetch = require('node-fetch').default; // 与浏览器行为一致
  const resp = await fetch('http://my.test/a', { redirect: 'follow' });

  expect(resp.url).toBe('http://my.test/end'); // 最终 URL
  expect(resp.status).toBe(200);
  const data = await resp.json();
  expect(data).toEqual({ result: 'ok' });
});

如果想把“中间 URL”也记录下来,只需把 redirect 设为 manual,然后循环手动解析 Location:

test('手动跟随并记录重定向历史', async () => {
  const fetch = require('node-fetch').default;
  const history = [];
  let url = 'http://my.test/a';

  for (let i = 0; i < 10; i++) {
    const res = await fetch(url, { redirect: 'manual', timeout: 5000 });
    history.push({ url, status: res.status });
    if (res.status < 300 || res.status > 399) break;
    url = res.headers.get('Location');
  }

  expect(history).toHaveLength(4);
  expect(history[0]).toMatchObject({ url: 'http://my.test/a', status: 301 });
  expect(history[3]).toMatchObject({ url: 'http://my.test/end', status: 200 });
});

以上代码完全本地闭环,不依赖外网,可在任何国内 CI 镜像秒级通过。

拓展思考

  1. 如果后端返回 308 (Permanent Redirect) 且要求保持请求方法,你的测试用例是否覆盖了 POST 场景?
    提示:在 msw 里用 rest.post 模拟,然后断言请求体是否被原样转发。

  2. 当接口需要携带登录 cookie 时,如何验证 302 过程中 cookie 不会丢失?
    提示:在 fetch 里加 credentials: 'include',并在 msw 路由里用 req.headers.get('cookie') 断言。

  3. 在 React 项目里,如果组件内使用 axios 且配置了 axios-retry,你如何确保“重定向链”与“重试次数”不会互相干扰?
    提示:用 jest.spyOn(axios, 'request') 记录调用次数,同时用 msw 返回 502→301→200 的混合序列,验证最终成功只有一次 retry。

  4. 如果公司强制要求“所有测试必须走真实浏览器”,你会如何用 Jest + Puppeteer 做到“本地并行不串口”?
    提示:jest-puppeteer 的 browserContext 每用例新开隐身上下文,配合 page.setRequestInterception(true) 收集跳转链,CI 里加 --disable-dev-shm-usage 防止容器内存不足。

把上面四点预演一遍,基本就能在国内前端单测面试的“重定向”话题里拿到满分。