如何解决route.params未定义的问题?

3

我在我的代码中有这一部分,我想要测试,但是当我运行测试时route.params听起来像是错误的:

 onMounted(async () => {
        try {
          const { tokenId } = route.params

在获取 URL 中的 ID 时,通常会使用 IT 技术。但是,在测试时我遇到了以下错误:

错误类型:TypeError: Cannot read property 'params' of undefined。

这是我的测试代码:

beforeEach(() => {
  wrapper = shallowMount(App, {
    mocks: {
      route: {
          params: {
            id: 'id'
          }
        }
    },
    global: {
      plugins: [store],
    },
    computed: { notFound: () => {} },
  })
})

路由或$route? - jeremy castelli
@jeremycastelli 是路由。 - signup
1个回答

2
您的mocks.route并没有进行模拟。
import { useRoute } from 'vue-router'
//...

setup() {
  const route = useRoute();
  //...
}

如果你想详细了解如何使用vue3组合式api设置测试各种与路由相关的情况,可以参考这里提供的示例。


为了简单地使你的组件在useRoute()返回undefined时不会失败,你可以使用以下代码:

const { tokenId } = route?.params || {};
if (tokenId) {
  // do your thing...
}

不需要使用 try


为了测试你的组件是否根据 tokenId 路由参数值执行了预期的操作,你应该在测试中模拟 vue-router,返回一个返回参数对象的函数:

这样应该可以正常工作:

jest.mock('vue-router', () => ({
  useRoute: () => ({ params: { id: 'id' } })
}));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接