Skip to content

Commit

Permalink
Add tests for derived state as keys
Browse files Browse the repository at this point in the history
  • Loading branch information
DAreRodz committed Jan 19, 2024
1 parent bbe13c2 commit 00650c7
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,28 @@
<p data-wp-text="context.item" data-testid="item"></p>
</div>
</div>


<div data-testid="derived state">
<button
data-testid="rotate" data-wp-on--click="actions.rotateFruits"
>Rotate</button>
<template
data-wp-context='{ "idPrefix": "fruit-" }'
data-wp-each--fruit="state.fruits"
data-wp-each-key="state.fruitId"
>
<p
data-testid="item"
data-wp-text="context.fruit"
data-wp-bind--data-fruit-id="state.fruitId"
></p>
</template>
<!-- SSRed elements; they should be removed on hydration -->
<p data-testid="item" data-wp-each-child>avocado</p>
<p data-testid="item" data-wp-each-child>banana</p>
<p data-testid="item" data-wp-each-child>cherimoya</p>
</div>
</div>

<hr>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ store( 'directive-each', {
store( 'directive-each', {
state: {
fruits: [ 'avocado', 'banana', 'cherimoya' ],
get fruitId() {
const { idPrefix, fruit } = getContext();
return `${idPrefix}${fruit}`;
}
},
actions: {
removeFruit() {
Expand Down
33 changes: 33 additions & 0 deletions test/e2e/specs/interactivity/directive-each.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -450,4 +450,37 @@ test.describe( 'data-wp-each', () => {
await expect( elements ).toHaveCount( 1 );
await expect( elements ).toBeEmpty();
} );

test( 'should work with derived state as keys', async ( { page } ) => {
const elements = page
.getByTestId( 'derived state' )
.getByTestId( 'item' );

// These tags are included to check that the elements are not unmounted
// and mounted again. If an element remounts, its tag should be missing.
await elements.evaluateAll( ( refs ) =>
refs.forEach( ( ref, index ) => {
if ( ref instanceof HTMLElement ) {
ref.dataset.tag = `${ index }`;
}
} )
);

await page
.getByTestId( 'derived state' )
.getByTestId( 'rotate' )
.click();

await expect( elements ).toHaveText( [
'cherimoya',
'avocado',
'banana',
] );

// Get the tags. They should not have disappeared or changed.
const [ cherimoya, avocado, banana ] = await elements.all();
await expect( cherimoya ).toHaveAttribute( 'data-tag', '2' );
await expect( avocado ).toHaveAttribute( 'data-tag', '0' );
await expect( banana ).toHaveAttribute( 'data-tag', '1' );
} );
} );

0 comments on commit 00650c7

Please sign in to comment.