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

Vue test-utils how to test a router.push()

在我的组件中,我有一个方法将执行 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 成员。您可以从 this 调用它,而不是直接导入路由器并调用它的 push,因为 $router:

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

现在,这使测试更容易,因为您可以在测试时通过 mocks 属性 将假路由器传递给您的组件,就像您对 [=17= 所做的那样] 已经:

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

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

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

假设您已经正确设置了先决条件并且类似于 this

只需使用

it("should ... go to home page", async () => {
    const $route = {
      name: "home"
    }

  ...

  // router path '/home' to be called ?
  expect(wrapper.vm.$route.name).toBe($route.name)
});