【问题标题】:Testing svelte components that use slots测试使用插槽的苗条组件
【发布时间】:2020-07-01 10:31:36
【问题描述】:

我正在使用Testing Library 作为一个苗条应用程序的一部分,总的来说它运行良好。但是,我有一个将数组作为道具的组件,使用输入对其进行过滤,然后将过滤后的数组传递给插槽。我想测试插槽是否接收到正确过滤的数组。我认为设置一个虚拟插槽将是可行的方法,然后只需使用 getByText 来确保页面中只有正确的元素。

组件代码:

<script>
  export let list = [{ name: 'Adam' }];

  let filter = "";

  $: filteredList = list.filter(({ name }) => name.includes(filter));
</script>

<span class="wrapper">
  <input
    bind:value={filter}
    name={fieldName}
    type="search" />
</span>
<slot {filteredList} />

【问题讨论】:

    标签: unit-testing testing svelte svelte-3 testing-library


    【解决方案1】:

    遗憾的是,Svelte 还没有办法在组件 API 中声明插槽。您需要创建一个单独的组件来导入您要测试的组件,然后您可以针对包装的组件进行测试。你可以在这里了解更多关于这个问题的信息https://github.com/testing-library/svelte-testing-library/issues/48#issuecomment-522029988

    您的示例可能如下所示:

    <!-- TestComponentWrapper.svelte -->
    export const slotContent = undefined;
    
    <Component>
      {slotContent} // This could also just be hardcoded to something you want if it doesn't need to be dynamic
    </Component>
    
    <!-- Component.test.js -->
    import TestComponentWrapper from './TestComponentWrapper.svelte';
    
    const { container } = render(
      TestComponentWrapper, 
      { props: { slotContent: 'Some Content' } }
    );
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2022-08-12
      • 2022-01-23
      • 2020-10-05
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      相关资源
      最近更新 更多