I’m using the webpack template generated by Vue’s CLI and have been trying to add some unit tests. And example has already been provided and it works perfectly:
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') }) })
Then I try to add another test which I copied straight from Vue’s documentation (Documentation link) but something weird happened:
// Inspect the raw component options it('has a created hook', () => { console.log(typeof Hello.created) expect(typeof Hello.created).toBe('function') })
I got the following error:
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
So it seems like Hello.created
gives me an undefined
, but as you can see, I also console.log
it to double check, and it does give it the desired result: undefined
Can anyone give me some help on what happened and how to fix it? I’ve already tried the solution here and still couldn’t make it work.
For your reference, here’s how Hello.vue
looks like:
<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>
Advertisement
Answer
Turns out the template is actually using chai instead of jasmine to do unit test.
In this case,
expect(typeof Hello.created).to.equal('function')
or
expect(Hello.created).to.be.a('function')
both work.