【问题标题】:Cannot find data-testid attribute in Vue Component with Jest在带有 Jest 的 Vue 组件中找不到 data-testid 属性
【发布时间】:2020-07-15 07:03:51
【问题描述】:

我正在尝试构建一个针对具有 data-testid 属性的元素的测试。我有一个看起来像这样的 BaseTile 组件:

<template>
      <div
        data-testid="base-tile-icon"
        v-if="!!this.$slots.icon"
      >
        <slot name="icon"></slot>
      </div>
</template>

<script>
export default {};
</script>

<style></style>

我的测试是这样的:

import { mount } from '@vue/test-utils';
import BaseTile from '@/components/BaseTile';

const factory = (slot = 'default') => {
  return mount(BaseTile, {
    slots: {
      [slot]: '<div class="test-msg"></div>'
    }
  });
};

it('has an icon slot if an icon is provided', () => {
  let wrapper = factory({ slot: 'icon' });
  const input = wrapper.find('[data-testid="base-tile-icon"]');
  expect(input.findAll('.test-msg').length).toBe(1);
});

如何在此测试中适当地定位 data-testid 属性?

【问题讨论】:

    标签: vue.js jestjs


    【解决方案1】:

    工厂的命名参数实现不正确。正确的方法在这篇文章中描述:Is there a way to provide named parameters in a function call in JavaScript?

    正确的实现方式如下:

    import { mount } from '@vue/test-utils';
    import BaseTile from '@/components/BaseTile';
    
    const factory = ({ slot = 'default' } = {}) => {
      return mount(BaseTile, {
        slots: {
          [slot]: '<div class="test-msg"></div>'
        }
      });
    };
    
    it('has an icon slot if an icon is provided', () => {
      let wrapper = factory({ slot: 'icon' });
      const input = wrapper.find('[data-testid="base-tile-icon"]');
      expect(input.findAll('.test-msg').length).toBe(1);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 2019-12-14
      • 2020-03-23
      • 2019-07-07
      • 1970-01-01
      • 2019-10-19
      • 2020-05-17
      相关资源
      最近更新 更多