我可以使用vue test utils通过引用选择一个元素吗?

时间:2019-04-01 13:00:13

标签: vuejs2 jestjs vue-test-utils refs

如果我有图片

<img class="pineapple" ref="pineapple" src="pineapple.jpg" />

我可以使用$ ref

expect(wrapper.find($refs.pineapple).exists()).toBe(true)

代替

expect(wrapper.find('.pineapple').exists()).toBe(true)

2 个答案:

答案 0 :(得分:0)

您在这里拥有出色的example

var Approvals = {
  props: ['someContent'],
  components: {
    'vue-toast': VueToast
  },
  methods: {
    showToast() {
      const toast = this.$refs.toast;
      toast.showToast(this.someContent);
    }
  },
  mounted() {
    console.log(this.$refs);
    this.$refs.toast.setOptions({
      maxToasts: 3,
      position: 'bottom right'
    });
  }
}

// specs code
describe('Approvals page', () => {
    const wrapper = shallow(Approvals);

    it('any test', () => {
        expect(wrapper).toBeDefined();
    });
});

Source

答案 1 :(得分:0)

您可以使用wrapper.find属性将对象传递到ref

expect(wrapper.find({ref: 'pineapple'}).exists()).toBe(true)

从Vue Test实用程序文档中:

查找选项对象

参考

通过使用find选项对象,Vue Test Utils允许通过$ ref在包装器组件上选择元素。

const buttonWrapper = wrapper.find({ ref: 'myButton' })
buttonWrapper.trigger('click')

https://vue-test-utils.vuejs.org/api/selectors.html

相关问题