mirror of https://github.com/sveltejs/svelte
Test array sort in effect to prevent regressions of this use-case (#16175)
parent
579d0e6636
commit
de90fc8dce
@ -0,0 +1,52 @@
|
|||||||
|
import { flushSync } from 'svelte';
|
||||||
|
import { test } from '../../test';
|
||||||
|
|
||||||
|
export default test({
|
||||||
|
/**
|
||||||
|
* Ensure that sorting an array inside an $effect works correctly
|
||||||
|
* and re-runs when the array changes (e.g., when items are added).
|
||||||
|
*/
|
||||||
|
test({ assert, target }) {
|
||||||
|
const button = target.querySelector('button');
|
||||||
|
|
||||||
|
// initial render — array should be sorted
|
||||||
|
assert.htmlEqual(
|
||||||
|
target.innerHTML,
|
||||||
|
`
|
||||||
|
<button>add item</button>
|
||||||
|
<p>0</p>
|
||||||
|
<p>50</p>
|
||||||
|
<p>100</p>
|
||||||
|
`
|
||||||
|
);
|
||||||
|
|
||||||
|
// add first item (20); effect should re-run and sort the array
|
||||||
|
flushSync(() => button?.click());
|
||||||
|
|
||||||
|
assert.htmlEqual(
|
||||||
|
target.innerHTML,
|
||||||
|
`
|
||||||
|
<button>add item</button>
|
||||||
|
<p>0</p>
|
||||||
|
<p>20</p>
|
||||||
|
<p>50</p>
|
||||||
|
<p>100</p>
|
||||||
|
`
|
||||||
|
);
|
||||||
|
|
||||||
|
// add second item (80); effect should re-run and sort the array
|
||||||
|
flushSync(() => button?.click());
|
||||||
|
|
||||||
|
assert.htmlEqual(
|
||||||
|
target.innerHTML,
|
||||||
|
`
|
||||||
|
<button>add item</button>
|
||||||
|
<p>0</p>
|
||||||
|
<p>20</p>
|
||||||
|
<p>50</p>
|
||||||
|
<p>80</p>
|
||||||
|
<p>100</p>
|
||||||
|
`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
@ -0,0 +1,21 @@
|
|||||||
|
<script>
|
||||||
|
let arr = $state([100, 0, 50]);
|
||||||
|
let nextValues = [20, 80];
|
||||||
|
let valueIndex = 0;
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
arr.sort((a, b) => a - b);
|
||||||
|
});
|
||||||
|
|
||||||
|
function addItem() {
|
||||||
|
if (valueIndex < nextValues.length) {
|
||||||
|
arr.push(nextValues[valueIndex]);
|
||||||
|
valueIndex++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<button onclick={addItem}>add item</button>
|
||||||
|
{#each arr as x}
|
||||||
|
<p>{x}</p>
|
||||||
|
{/each}
|
Loading…
Reference in new issue