使用 Jest 测试 Vue 时访问变量

时间:2021-04-08 09:09:13

标签: vue.js testing jestjs

我在我的 Vue.js Web 应用程序中使用以下结构。我现在正在尝试对其进行测试。但是在尝试测试 exampleOfFunction 时,它说 this.exampleOfData2undefined

<template>
      *Some HTML*
</template>

<script>
    *Some Imports*
export default {
    data() {
        return {
            exampleOfData1: [],
            exampleOfData2: 100
     },
        methods: {
        exampleOfFunction:function(){
            if(this.exampleOfData2 === 100)
            {
                return false;
            }
            return true;
        },
    created() {
    },
    mounted() {
    }
 }
</script>

在我的测试文件中,我尝试访问上面的代码,我成功使用 console.log(FileToTest.data()); 我可以看到数据的值,我可以使用 FileToTest.methods.exampleOfFunction(); 访问该函数,但是当我调用该函数时,它说this.exampleOfData2undefined

1 个答案:

答案 0 :(得分:0)

看起来您在测试中使用的是组件选项定义而不是组件实例。

您应该通过 mounting the component 创建包装器,然后您可以通过 wrapper.vm 访问组件方法:

import { shallowMount } from '@vue/test-utils'
import FileToTest from '@/components/FileToTest.vue'

describe('FileToTest', () => {
  it('exampleOfFunction returns false by default', () => {
    const wrapper = shallowMount(FileToTest)
    expect(wrapper.vm.exampleOfFunction()).toBe(false)
  })

  it('exampleOfFunction returns true when data is not 100', () => {
    const wrapper = shallowMount(FileToTest)
    wrapper.setData({ exampleOfData2: 0 })
    expect(wrapper.vm.exampleOfFunction()).toBe(true)
  })
})