如何测试来自组件中另一个模块的自定义指令

Kev*_* T. 5 javascript vue.js jestjs vuejs2 vue-test-utils

我有一个 UI 库,可以导入到我们的应用程序中。在 UI 库中有一个自定义指令 ,toggle我们使用它来打开和关闭模态。当我运行单元测试时,我收到此错误:

[Vue warn]: Failed to resolve directive: toggle

      (found in <Identity>)
Run Code Online (Sandbox Code Playgroud)

在我的Identity组件中,我使用了 UI 库中的一个组件checkbox,它包含了这个指令:

[Vue warn]: Failed to resolve directive: toggle

      (found in <Identity>)
Run Code Online (Sandbox Code Playgroud)

如何在我的Identity.spec.js? 导入后,我有:

const localVue = createLocalVue()

localVue.use(Vuex)
localVue.use('toggle') 
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 11

@vue/test-utils1.x 中,shallowMountand的第二个参数mount接受一个directives选项,该选项定义要在组件中使用的指令。在 2.x 中,选项是global.directives. 您可以使用此选项来声明v-toggle指令:

shallowMount(MyComponent, {
  // @vue/test-utils @1.x
  directives: {
    toggle() { /* stub */ }
  },

  // @vue/test-utils @2.x
  global: {
    directives: {
      toggle() { /* stub */ }
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

例如,要确保在组件中使用指令:

const toggle = jest.fn()

shallowMount(MyComponent, {
  // @vue/test-utils @1.x
  directives: {
    toggle
  },

  // @vue/test-utils @2.x
  global: {
    directives: {
      toggle() { /* stub */ }
    }
  }
})

expect(toggle).toHaveBeenCalled()
Run Code Online (Sandbox Code Playgroud)