【问题标题】:Getting access to varaibles when testing Vue with Jest使用 Jest 测试 Vue 时访问变量
【发布时间】:2021-07-04 03:15:08
【问题描述】:

我在我的 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

【问题讨论】:

  • FileToTest 到底是什么?如果这是您导入的组件定义,那么您正在以错误的方式对其进行测试。 Vue 在您不这样做时将方法绑定到实例,在不符合实际行为的测试中没有多大价值。

标签: vue.js testing jestjs


【解决方案1】:

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

您应该通过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)
  })
})

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 1970-01-01
    • 2019-05-28
    • 2020-08-04
    • 2019-08-12
    • 2020-04-17
    • 2018-07-02
    • 2019-07-23
    • 2018-06-01
    相关资源
    最近更新 更多