[英]error in unit test vue.js karma : undefined is not a constructor ()
[英]error in unit test vue.js karma (webpack): undefined is not a constructor
我正在使用 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 的文档(文档链接)中复制了它,但是发生了一些奇怪的事情:
// 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
任何人都可以就发生的事情以及如何解决它给我一些帮助吗? 我已经在这里尝试了解决方案,但仍然无法使其工作。
供您参考,下面是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>
原来模板实际上是使用 chai 而不是 jasmine 来进行单元测试。
在这种情况下,
expect(typeof Hello.created).to.equal('function')
或者
expect(Hello.created).to.be.a('function')
两者都有效。
对我来说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);
})
})
这对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.