【问题标题】:Unit Test Vue Component Rails App单元测试 Vue 组件 Rails 应用程序
【发布时间】:2016-11-11 01:57:19
【问题描述】:

我已经使用这种结构创建了 vue 组件。

Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})

我想使用 karma 和 jasmine 或 jasmine rails gem 对此进行测试。我不知道如何测试组件。在文档上的所有示例中,他们使用 requirejs 模块的测试方式。我使用全局组件的方式来创建组件。

这些是文档中的示例。

<template>
  <span>{{ message }}</span>
</template>
<script>
  export default {
    data () {
      return {
        message: 'hello!'
      }
    },
    created () {
      this.message = 'bye!'
    }
  }
</script>

// Import Vue and the component being tested
import Vue from 'vue'
import MyComponent from 'path/to/MyComponent.vue'

// Here are some Jasmine 2.0 tests, though you can
// use any test runner / assertion library combo you prefer

describe('MyComponent', () => {
  // Inspect the raw component options
  it('has a created hook', () => {
    expect(typeof MyComponent.created).toBe('function')
  })
  // Evaluate the results of functions in
  // the raw component options
  it('sets the correct default data', () => {
    expect(typeof MyComponent.data).toBe('function')
    const defaultData = MyComponent.data()
    expect(defaultData.message).toBe('hello!')
  })
  // Inspect the component instance on mount
  it('correctly sets the message when created', () => {
    const vm = new Vue(MyComponent).$mount()
    expect(vm.message).toBe('bye!')
  })
  // Mount an instance and inspect the render output
  it('renders the correct message', () => {
    const Ctor = Vue.extend(MyComponent)
    const vm = new Ctor().$mount()
    expect(vm.$el.textContent).toBe('bye!')
  })
})

【问题讨论】:

    标签: ruby-on-rails vue-component vue.js


    【解决方案1】:

    import foo from 'bar';var foo = require('bar'); 做同样的事情,使foo 在当前文件中作为变量可用。测试示例中MyComponent是导入的vue组件实例,也可以在当前文件中用MyComponent = Vue.component(...);实现。因此,如果您的测试在同一个文件中,只需使用MyComponent 变量,如果没有,您需要先导出MyComponentmodule.exports = MyComponentexport default MyComponent。这些导出假设 MyComponent 是您要导出的唯一内容,如果您要导出多个变量,请查看文档:http://wiki.commonjs.org/wiki/Modules/1.1 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/export

    【讨论】:

      猜你喜欢
      • 2019-04-18
      • 2020-12-02
      • 2019-01-02
      • 1970-01-01
      • 2023-01-03
      • 2019-03-20
      • 2020-10-16
      • 2019-12-25
      • 2021-02-05
      相关资源
      最近更新 更多