在我的组件中,我有一个方法可以执行一个router.push()

import router from "@/router";
// ...
export default {
  // ...
  methods: {
    closeAlert: function() {
      if (this.msgTypeContactForm == "success") {
        router.push("/home");
      } else {
        return;
      }
    },
    // ....
  }
}

我想测试一下...

我写了以下规格..

it("should ... go to home page", async () => {
    // given
    const $route = {
      name: "home"
    },
    options = {
      ...
      mocks: {
        $route
      }
    };
    wrapper = mount(ContactForm, options);
    const closeBtn = wrapper.find(".v-alert__dismissible");
    closeBtn.trigger("click");
    await wrapper.vm.$nextTick();
    expect(alert.attributes().style).toBe("display: none;")
    // router path '/home' to be called ?
  });

1-我出错了

console.error node_modules/@vue/test-utils/dist/vue-test-utils.js:15
[vue-test-utils]: could not overwrite property $route, this is usually caused by a plugin that has added the property asa read-only value

2-如何编写expect()以确保已调用此/主路由

感谢您的反馈

推荐答案

你正在做一些碰巧能正常工作的事情,但我认为这是错误的,而且也给你测试路由带来了问题.您正在组件中导入路由:

import router from "@/router";

然后马上拨打push:

router.push("/home");

我不知道你是如何安装路由的,但通常你会这样做:

new Vue({
  router,
  store,
  i18n,
}).$mount('#app');

安装Vue插件.我打赌你已经在这么做了(事实上,这是一种向你的组件expose $route的机制).在本例中,还安装了vuex存储和对vue-i18n的引用.

这将expose all your components中的$router个成员.不必导入路由并直接调用其push,您可以从this将其称为$router:

this.$router.push("/home");

现在,thise使测试更容易,因为在测试时,您可以通过mocks属性将假路由传递到组件,就像您已经在使用$route一样:

  const push = jest.fn();
  const $router = {
    push: jest.fn(),
  }
  ...
  mocks: {
    $route,
    $router,
  }

然后,在你的测试中,你断言push被调用:

  expect(push).toHaveBeenCalledWith('/the-desired-path');

Vue.js相关问答推荐

VueUse onClickOutside不支持右键单击

Vuetify 3 v-radio-group 将模型设置为 null

Vuejs 通过数据键迭代复杂对象

如果似乎没有明确使用输入事件,那么发出输入事件有什么作用?

v-slot: activator 中 {attrs} 参数的作用是什么?

Vuejs 和 Laravel 发布请求 CORS

VueJS - 将单独的组件加载到 vue 实例中

VueJS中的绑定函数含义

如何使用 Vue 命名插槽呈现静态内容列表?

VueJS:向左,元素的顶部位置?

Vue 3 - 带有全局组件的无法解析组件

如何使用 vuex 删除项目?

使用vue.js单击时如何获取按钮的值

VueJS错误编译模板

如何在 vuetify 中将工具提示添加到数据表标题?

在Vue中单击路由链接上的激活方法

未在实例上定义,但在渲染期间引用

将 ref 的内容从子组件传递到另一个 VueJS 子组件

Vue Cli 3:定义的输出路径

Vue v-model 不响应 BS4 单选按钮组