【问题标题】:Vue test-utils how to test a router.push()Vue test-utils 如何测试 router.push()
【发布时间】:2019-04-17 13:22:21
【问题描述】:

在我的组件中,我有一个方法可以执行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 路由已被调用

感谢反馈

【问题讨论】:

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


    【解决方案1】:

    您正在做的事情碰巧可以工作,但我认为这是错误的,并且还会导致您在测试路由器时遇到问题。您正在组件中导入路由器:

    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");
    

    现在,thise 简化了测试,因为您可以在测试时通过 mocks 属性将假路由器传递给您的组件,就像您已经使用 $route 所做的那样:

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

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

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

    【讨论】:

    • 你是对的......我安装了你提到的路由器......我更明白为什么我不能模拟路由器......!非常感谢我现在要测试它.. $route 应该如何定义?
    • 我仍然收到[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】:

    假设您已经正确设置了先决条件并且类似于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)
    });
    

    【讨论】:

    • 非常感谢 ... 它适用于:expect(wrapper.vm.$route.name).toBe($route.name) ... not $rout.path
    • 糟糕,抱歉。 $route.path 是我用过的,也是肌肉记忆。我希望这对你有所帮助
    猜你喜欢
    • 2021-04-03
    • 2019-10-24
    • 2021-02-17
    • 2018-09-28
    • 2018-11-09
    • 2021-11-26
    • 2019-07-16
    • 1970-01-01
    • 2021-09-11
    相关资源
    最近更新 更多