简体   繁体   English

Vue.js单元测试-如何检查组件是否具有方法?

[英]Vue.js Unit Test - How to check if component has a method?

I have a simple component with one method in it. 我有一个带有一种方法的简单组件。 I would like to check if a method in it exists. 我想检查其中是否存在方法。 I know that I can check, if a component contains a certain class or a string, but can't figure out how to check for a method's name. 我知道我可以检查组件是否包含某个类或字符串,但无法弄清楚如何检查方法的名称。 Couldn't find any simple explanation. 找不到任何简单的解释。

Component to test: 要测试的组件:

<template>
    <div>
      <a id="returnButton" href="#" @click="toMainList" class="d-flex align-items-center back-to-button">
          <font-awesome-icon :icon="['fas', 'arrow-left']" class="fontBasicIcon back-to-button-icon" />
          <div>Back</div>
      </a>
    </div>
</template>

<script>
    import router from '@/router'

    export default {
        name: 'back-to-button',
        data () {
            return {
            }
        },
        methods:{
            toMainList(){
                $router.push('/mainlist');
            }
        }
    }
</script>

Assuming you use Jest and mount your component to test via shallowMount or mount , the wrapper returned gives you access to the Vue instance (including all it's methods) 假设您使用Jest并通过shallowMountmount来安装组件以进行测试,则返回的包装shallowMount您可以访问Vue实例(包括其所有方法)

const wrapper = shallowMount(Foo)
let instance = wrapper.vm // <- the Vue instance
let myMethod = instance.myMethod // <- a method callend 'myMethod' on the Vue instance

if(myMethod != undefined) {
  console.log("method 'myMethod' exists")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何对依赖复杂Vuex存储并扩展另一个组件的Vue.js组件进行单元测试? - How do I unit test a Vue.js component that relies on a complicated Vuex store and extends another component? 如何使用返回任何元素数组的渲染函数对 Vue.js 功能组件进行单元测试? - How do you unit test a Vue.js functional component with a render function that returns any array of elements? 如何在 vue.js 单元测试中模拟 window.google - How to mock window.google in a vue.js unit test 如何对依赖外部依赖项的vue.js中的组件进行单元测试? - how to unit test components in vue.js that rely on external dependencies? 使用 Jest,在 vue.js 中对单个文件组件进行单元测试时如何窥探扩展组件的方法 - Using Jest, how do I spyon an extended component's method when unit testing a single file component in vue.js 如何测试 vue.js v-select 组件的值 - How to test value of vue.js v-select component Vue.js:如何在方法中使用来自另一个组件的变量 - Vue.js: How to Use a Variable from Another Component in a Method 如何在 Vue.JS 中使用 axios 方法填充组件的数据 - How to populate component's data with axios method in Vue.JS Vue.js - 如何从另一个组件调用方法 - Vue.js - How to call method from another component Vue.js:检查组件是否存在 - Vue.js: check if a component exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM