vue.js - Vue test-utils 如何测试 router.push()

标签 vue.js vue-router vue-test-utils

在我的组件中,我有一个方法将执行 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() 以确保此/home 路由已被调用

感谢反馈

最佳答案

您正在做的事情恰好有效,但我认为这是错误的,并且还会导致您在测试路由器时遇到问题。您正在组件中导入路由器:

import router from "@/router";

然后调用它的 push马上:

router.push("/home");

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

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

安装 Vue 插件。我打赌你已经在这样做了(事实上,这种机制将 $route 暴露给你的组件)。在示例中,还安装了 vuex 商店和对 vue-i18n 的引用。

这将公开一个 $router 所有组件中的成员。而不是导入路由器并调用其 push直接,你可以从this调用它作为$router :

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

现在,这使测试更容易,因为您可以在测试时通过 mocks 将伪造的路由器传递给您的组件。属性(property),就像你对 $route 所做的一样已经:

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

然后,在您的测试中,您针对 push 断言被称为:

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

关于vue.js - Vue test-utils 如何测试 router.push(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53302536/

相关文章:

javascript - 无法使用 Laravel Mix 在 Vue 组件中访问 js-cookie

javascript - 如何在vue.js循环中实现运行平衡?

vue.js - 如何使用 Konva 将移除的形状拉回到场景中?

vue.js - 如何在 vue-test-utils 上测试 Vue-Property-Decorator 的 @InjectReactive()?

javascript - vue.runtime.common.js : "Cannot read property ' _transitionClasses' of undefined"when this. 错误未使用

vue.js - 在组件导航守卫中测试 Vue Router

vue.js - Vue 动态组件和动态 props

javascript - 使用 vue 和 vue-router 确保 View 顺序的最佳实践

vue.js - Vuejs + vue-router,在 View 之间传递数据,如http post

vue.js - vuejs : router-link params is empty