我有一个非常小的Vue项目,看起来像这样:
待测试文件: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>
而jest测试文件看起来像:
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)
})
})
当我用$ npm run test:unit
运行测试时,我得到了错误:
-- 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)
看起来this
在以下两种情况下的作用不同:
- (
this = Sum.methods
( - 在实现代码(
this = [Sum.data, Sum.methods, Sum.render]
(中
所以我的问题是:
如何对引用data
变量的方法进行单元测试?(就像上面的代码一样(
非常感谢!
好的,我明白了。
感谢@Alexander Staroselsky,我应该在代码中使用wrapper.vm
而不是"Sum"。
正确的单元测试文件应该是:
import { shallowMount } from "@vue/test-utils"
import Sum from '@/views/Sum.vue'
describe('Sum.vue', () => {
it('should run sum', () => {
// expect(Sum.methods.sum()).toBe(3) <-- here I used Sum.methods.sum()
// below is correct.
const wrapper = shallowMount(Sum)
expect(wrapper.vm.sum()).toBe(3)
})
})
wrapper.vm
是一个有趣的对象,你可以直接访问变量和方法,比如:
wrapper.vm.a # => vue.data.a
wrapper.vm.b # => vue.data.b
wrapper.vm.sum # => vue.methods.sum
所以代码shallowMount()
非常重要,无论你想不想测试HTML输出,你都应该写这行代码。