spirift
spirift

Reputation: 3072

Testing svelte components that use slots

I am using Testing Library as part of a svelte app and on the whole it's working very well. However I have a component that takes an array as a prop, filters it with an input and then passes the filtered array on to a slot. I would like to test that the slot receives the correctly filtered array. I'm thinking that setting up a dummy slot would be the way to go and then simply use getByText to make sure only the correct elements are in the page.

Component code:

<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} />

Upvotes: 5

Views: 1859

Answers (1)

Austin Knight
Austin Knight

Reputation: 103

Svelte doesn't have a way to declare slots in the component API yet unfortunately. You would need to create a separate component which imports the component you want to test and then you can test against the wrapped component. You can learn more about the issue here https://github.com/testing-library/svelte-testing-library/issues/48#issuecomment-522029988

Your example may look like this:

<!-- 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' } }
);

Upvotes: 2

Related Questions