您如何使用Jest测试Vue.js模态组件?

时间:2018-10-25 19:34:59

标签: testing vue.js jestjs

我有一个vuejs模式组件,该组件显示团队成员的模式(头像,全名和说明)。我需要测试。

teamMembers.js看起来像:

    <template lang="pug">
      .col-lg-4.col-md-6.team_member_wrapper
        a(href="javascript:;"  data-toggle="modal" data-target="#TeamMemberModal" @click="$emit('clicked', item)" )
          .team_member
            .team_member_image
              img(:src="item.avatar")
            .team_member_name {{item.full_name}}
            .team_member_status {{item.status}}
            .team_member_shadow
    </template>git status
    <script>
    export default {
      name: "TeamMember",
      props: {
        item: {},
      }
    };
    </script>

我的测试代码是:

import Vue from 'vue'
import  TeamMember  from '@/components/TeamMember.vue'
import {  mount } from '@vue/test-utils'


const wrapper = mount(TeamMember, {
  context: {
    props : {
        item : {
            avatar : 'path/to_image.png',
            full_name: "Robocop"
            }
        } 
    }
});

我需要验证模板是否生成了正确的html  -包装器必须包含Vue实例。我是这样做的:

wrapper.setProps({ avatar: 'path/to_image.png' }),
expect(wrapper.vm.avatar).toBe('path/to_image.png'),


wrapper.setProps({ avatar: 'Robocop' }),
expect(wrapper.vm.full_name).toBe('Robocop')

我运行测试,得到以下结果:

失败的测试/单位/规格/TeamMember.spec.js

  

●测试套件无法运行

[vue-test-utils]: mount.context can only be used when mounting a functional component

   9 |        item : {
  10 |            avatar : 'path/to_image.png',
> 11 |            full_name: "Robocop"
     |                                            ^
  12 |            }
  13 |        } 
  14 |    }

  at throwError (node_modules/@vue/test-utils/dist/vue-test-utils.js:11:9)
  at createInstance (node_modules/@vue/test-utils/dist/vue-test-utils.js:2847:5)
  at mount (node_modules/@vue/test-utils/dist/vue-test-utils.js:5639:18)
  at Object.<anonymous> (tests/unit/specs/TeamMember.spec.js:11:36)

我的代码有什么错误,我该如何纠正? 谢谢

1 个答案:

答案 0 :(得分:0)

您要传递的选项应该在对象的根目录上,并且props数据是通过propsData选项设置的:

const wrapper = mount(TeamMember, {
  propsData: {
    item: {
      avatar: 'path/to_image.png',
      full_name: 'Robocop'
    }
  }
})