I am using the Svelte Material UI select menu component to control whether some items are displayed in my Svelte project. I would like to test whether for a given input the correct items are being displayed. Unfortunately, I can't figure out how to query and click the Select
component in Testing Library and Vitest. I'm not sure if I don't have the right query, or if I don't have the right event.
Here's a simplifed example of my Svelte component:
import Select, { Option } from '@smui/select';
const shapes = {
'square': 'square',
'rectangle': 'square',
'thin rectangle': 'thin rectangle',
'cylinder': 'circle',
'semi-circle': 'semi-circle',
'triangle': 'triangle',
'arch': 'arch'
};
let value = 'square';
$: correctHole = shapes[value];
</script>
<div>
<Select
bind:value label="What hole does this shape go into?"
style="width: 400px"
data-testid="select-shape"
>
{#each Object.keys(shapes) as shape}
<Option value={shape}>{shape}</Option>
{/each}
</Select>
<pre class="status">It goes in the {correctHole} hole!</pre>
</div>
And here's the test I'm trying:
import { describe, it, expect } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/svelte';
import HoleSelect from '$lib/HoleSelect.svelte';
describe('Switch options', () => {
it('Can see the triangle hole', async () => {
render(HoleSelect);
await fireEvent.click(screen.getByTestId('select-shape'));
await fireEvent.click(screen.getByText('triangle'));
expect(screen.getByText('It goes in the triangle hole!')).toBeInTheDocument();
});
});
This test fails, with the text I'm expecting still being in its original state ("It goes in the square hole!") and the triangle list item unselected according to the output:
FAIL src/index.test.js > Switch options > Can see the triangle hole
TestingLibraryElementError: Unable to find an element with the text: It goes in the triangle hole!. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, script, style
...
<li
aria-disabled="false"
aria-selected="false"
class="mdc-deprecated-list-item"
data-value="triangle"
role="option"
style=""
tabindex="-1"
value="0"
>
<span
class="mdc-deprecated-list-item__ripple"
/>
triangle
</li>
...
<pre
class="status"
>
It goes in the
square
hole!
</pre>
This example can be found here: https://github.com/pcclarke/select-testing
- Is there some different combination of query and events I should be trying?
- Seeing as what I really what to test is how the component updates as
value
changes, is there a way I could change it directly instead of using theSelect
component?