I have a very small Vue project, looks like this:
the to be test file: src/views/Sum.vue
<template>
<div>
Sum of ({{a}},{{b}}) is: {{sum()}}
</div>
</template>
<script>
export default{
data: function(){
return {
a: 1,
b: 2
}
},
methods: {
sum: function(){
console.info("-- in Sum.vue, this: ", this)
return this.a + this.b
}
}
}
</script>
and the jest test file looks like:
import { shallowMount } from "@vue/test-utils"
import Sum from '@/views/Sum.vue'
describe('Sum.vue', () => {
it('should run sum', () => {
console.info("-- in sum.spec.js, Sum is: " )
console.info(Sum)
expect(Sum.methods.sum()).toBe(3)
})
})
when I ran the test by $ npm run test:unit
, I got errors:
-- in sum.spec.js, Sum is:
{ data: [Function: data],
methods: { sum: [Function: sum] },
render: [Function: render],
staticRenderFns: [] }
-- in Sum.vue, this: { sum: [Function: sum] }
● Sum.vue › should run sum
expect(received).toBe(expected) // Object.is equality
Expected: 3
Received: NaN
6 | console.info("-- in sum.spec.js, Sum is: " )
7 | console.info(Sum)
> 8 | expect(Sum.methods.sum()).toBe(3)
| ^
9 | })
10 | })
11 |
at Object.it (tests/unit/say_one.spec.js:8:31)
It looks like the this
acts different in this two context:
- in the spec (
this = Sum.methods
) - in the implementation code (
this = [Sum.data, Sum.methods, Sum.render]
)
so my question is:
How to make unit tests to the methods that referenced the data
variables? (just like the above code )
thanks so much!
wrapper.vm
instead ofSum
. what about you post an simple answer? so that I can accept it. – Siwei Shen 申思维 Nov 3 '19 at 8:26