当我进行单元测试时,Vue仅将“方法”导出到Jest,如何导出“数据”等?

时间:2019-11-03 06:20:23

标签: unit-testing vuejs2 jestjs

我有一个非常小的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>

开玩笑的测试文件如下:

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变量的方法进行单元测试? (就像上面的代码一样)

非常感谢!

1 个答案:

答案 0 :(得分:1)

好的,我明白了。

由于@Alexander Staroselsky,我应该在代码中使用Function CreateUniqueFileNameA(strPath As String, strFileName) As String Dim extPos As Integer Dim extension As String Dim fileName As String Dim resFilename As String Dim orderID As Long extPos = InStrRev(strFileName, ".") If extPos > 0 Then fileName = Left(strFileName, extPos - 1) extension = Right(strFileName, Len(strFileName) - extPos) orderID = 0 resFilename = strFileName Do While DoesFileExist(strPath & resFilename) orderID = orderID + 1 resFilename = fileName & " (" & CStr(orderID) & ")." & extension Loop End If CreateUniqueFileNameA = resFilename End Function 而不是`Sum'。

正确的单元测试文件应为:

wrapper.vm

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

因此无论您是否要测试HTML输出,代码wrapper.vm.a # => vue.data.a wrapper.vm.b # => vue.data.b wrapper.vm.sum # => vue.methods.sum 都非常重要,您应该编写此行代码。