You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vitest模拟$router.push在Vue单元测试中失效问题排查

Vue.js + Vitest 单元测试:401错误处理中$router.push未被调用问题

问题说明

在Vue.js应用中测试API调用的错误处理逻辑时遇到异常:组件内的fetchBlogPosts方法在API返回401(未授权)错误时,明明会执行this.$router.push('/login')并移除localStorage令牌,但Vitest单元测试显示push方法被调用0次(已确认代码进入了catch块)。

组件方法代码

async fetchBlogPosts() {
  try {
    const data = await getBlogPosts();
    if (data.posts != null) {
      this.posts = data.posts;
    }
  } catch (error) {
    if (error.response.status === 401) {
      this.$router.push('/login');
      localStorage.removeItem('blog_access_token');
    }
  }
}

单元测试代码

const mockTransactionsErrorResponse = (error = {}) => {
  axios.get.mockRejectedValue(error)
}

it.only('handles unauthorized error', async () => {
  const push = vi.fn();
  const $router = { push };

  // 模拟未授权错误响应
  mockTransactionsErrorResponse({
    response: {
       status: 401,
       data: 'Unauthorized'
    }
  })

  // 设置组件渲染
  const vuetify = createVuetify();
  render(BlogComponent, {
    global: {
      mocks: { $router },
      plugins: [vuetify]
    },
    mocks: {
      localStorage: {
        getItem: () => 'blog_access_token'
      }
    }
  });

  // 断言
  expect(push).toHaveBeenCalledWith('/login'); // 问题:此处未被调用
  expect(localStorage.removeItem).toHaveBeenCalledWith('blog_access_token');
});

错误信息

AssertionError: 预期"spy"被调用时传入参数: [ '/login' ]


内容的提问来源于stack exchange,提问作者Jessica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:03:17