【问题标题】:error in unit test vue.js karma (webpack): undefined is not a constructor单元测试 vue.js 业力(webpack)中的错误:未定义不是构造函数
【发布时间】:2017-05-10 01:09:49
【问题描述】:

我正在使用 Vue 的 CLI 生成的 webpack 模板,并且一直在尝试添加一些单元测试。并且已经提供了示例,并且效果很好:

import Vue from 'vue'
import Hello from '@/components/Hello'

describe('Hello.vue', () => {
  it('should render correct contents', () => {
    const Constructor = Vue.extend(Hello)
    const vm = new Constructor().$mount()
    expect(vm.$el.querySelector('.hello h1').textContent)
      .to.equal('Welcome to Your Vue.js App')
  })
})

然后我尝试添加另一个测试,该测试直接从 Vue 的文档 (Documentation link) 中复制,但发生了一些奇怪的事情:

// Inspect the raw component options
it('has a created hook', () => {
  console.log(typeof Hello.created)
  expect(typeof Hello.created).toBe('function')
})

我收到以下错误:

LOG LOG: 'function'
    ✗ has a created hook
    undefined is not a constructor (evaluating 'expect((0, _typeof3.default)(_Hello2.default.created)).toBe('function')')
webpack:///test/unit/specs/Hello.spec.js:16:38 <- index.js:75919:64

所以看起来Hello.created 给了我一个undefined,但正如你所看到的,我也console.log 仔细检查了它,它确实给了它想要的结果:undefined

任何人都可以就发生的事情以及如何解决它给我一些帮助吗?我已经尝试了here 的解决方案,但仍然无法正常工作。

供您参考,Hello.vue 的外观如下:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      message: 'hello!'
    }
  },
  created () {
    console.log('oh crap')
    this.message = 'bye!'
  }
}
</script>

【问题讨论】:

    标签: javascript unit-testing phantomjs karma-runner vuejs2


    【解决方案1】:

    原来模板实际上是使用 chai 而不是 jasmine 来做单元测试。

    在这种情况下,

    expect(typeof Hello.created).to.equal('function')

    或

    expect(Hello.created).to.be.a('function')

    两者都有效。

    【讨论】:

      【解决方案2】:

      对我来说 to.be 或 toBe 不起作用。相反,我以以下方式使用 .equal (以获取组件方法的返回):

      import Vue from 'vue'
      import SingleTask from '@/components/SingleTask'
      
      describe('SingleTask.vue', () => {
         it('should return true', () => {
           const Constructor = Vue.extend(SingleTask)
           const vm = new Constructor().$mount()
      
           expect(vm.forUnitTest()).equal(true);
         })
      })
      

      这对我有用

      【讨论】:

        猜你喜欢
        • 2017-06-06
        • 2016-10-05
        • 2016-04-26
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        • 2018-09-05
        • 2017-11-19
        • 2018-06-07
        相关资源
        最近更新 更多