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

断了今生、忘了曾经 提交于 2019-12-05 12:05:12

You are doing something that happens to work, but I believe is wrong, and also is causing you problems to test the router. You're importing the router in your component:

import router from "@/router";

Then calling its push right away:

router.push("/home");

I don't know how exactly you're installing the router, but usually you do something like:

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

To install Vue plugins. I bet you're already doing this (in fact, is this mechanism that expose $route to your component). In the example, a vuex store and a reference to vue-i18n are also being installed.

This will expose a $router member in all your components. Instead of importing the router and calling its push directly, you could call it from this as $router:

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

Now, thise makes testing easier, because you can pass a fake router to your component, when testing, via the mocks property, just as you're doing with $route already:

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

And then, in your test, you assert against push having been called:

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

Assuming that you have setup the pre-requisities correctly and similar to this

Just use

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

No problème I got it right... and I understand bettes thé this.$router usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!