代码之家  ›  专栏  ›  技术社区  ›  user762579

Vue test utils如何测试路由器。push()

  •  0
  • user762579  · 技术社区  · 7 年前

    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 ?
      });
    

    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路由

    感谢您的反馈

    3 回复  |  直到 7 年前
        1
  •  11
  •   Sergeon    7 年前

    你正在做的事情,碰巧工作,但我认为是错误的,也造成你的问题,以测试路由器。您正在组件中导入路由器:

    import router from "@/router";
    

    然后称之为 push 马上:

    router.push("/home");
    

    我不知道你到底是怎么安装路由器的,但通常你会这样做:

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

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

    $router . 而不是导入路由器并调用其 推 你可以直接从 this 作为 $路由器

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

    mocks 财产,就像你在做的一样 $路线 已经:

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

    被称为:

      expect(push).toHaveBeenCalledWith('/the-desired-path');
    
        2
  •  2
  •   Ru Chern Chong ABHINAV    7 年前

    假设您已经正确地设置了前提条件,并且类似于 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)
    });
    
    推荐文章