Vue test-utils如何使用vuetify测试导航栏按钮

时间:2018-12-20 07:43:37

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

在我的导航栏组件中,我有一个执行 router.push()

的方法

methods: {
  redirectToScreen(payload) {
    this.$router.push({ name: `${payload}` });
  }
}

然后这是我的模板

<template lang="pug">
  v-toolbar#nav-toolbar(
    app
    :clipped-left="clipped"
    color="white"
    height="80px"
    fixed
  )
    v-toolbar-items

      //- ADMIN_OPD
      v-btn.admin-outpatient-event(
        flat
        v-if="userRole === 'ADMIN_OPD'"
        @click="redirectToScreen('admin-new-customer')"
      ) OUTPATIENT
      v-btn.admin-register-event(
        flat
        v-if="userRole === 'ADMIN_OPD'"
        @click="openRegisterAlert()"
      ) Register
</template>

我想用以下规格测试此代码

describe("Navbar.vue", () => {
  var wrp

  const localVue = createLocalVue();

  const spy = jest.fn();

  localVue.use(Vuetify);
  localVue.use(VueRouter);

  var router = new VueRouter({
    routes
  })

  beforeEach(() => {
    wrp = shallowMount(Navbar , {
      localVue,
      router,
      computed: {
        dataToken() {
          return "123124asd"
        },
        userRole() {
          return "ADMIN_OPD";
        },
        financeOnly() {
          return true;
        }
      }
    })
  })

  it("should redirect to admin-opd if navbar button got clicked", () => {
      wrp.vm.$router.push = spy;
      wrp.find(".admin-outpatient-event").trigger("click");
      expect(spy).toHaveBeenCalledWith({ name: 'admin-new-customer' });
  });
});

但不幸的是我遇到了错误

Expected mock function to have been called with:
  [{"name": "admin-new-customer"}]
But it was not called.

我应该如何编写测试Expect()以确保已调用“名称”:“ admin-new-customer”路由

感谢您的反馈

1 个答案:

答案 0 :(得分:0)

也许可以在throw spy.mock.calls之前尝试expects()Jest mock calls)来查看调用间谍的参数。
如果没有参数,则不会调用该间谍,并且触发单击和推送时出了点问题。
否则代码对我来说看起来不错。