fix(migrations): handle empty ngSwitchCase (#56105)

empty ngSwitchCase generate `case ()` which isn't valid syntax therefore adding quotes will help prevent us migrate empty case if no condition was provided

fix angular#56030

PR Close #56105
This commit is contained in:
naaajii 2024-05-27 22:19:06 +05:00 committed by Pawel Kozlowski
parent e5a6f91722
commit 3b2f88cd90
2 changed files with 29 additions and 1 deletions

View file

@ -94,7 +94,9 @@ function migrateNgSwitchCase(etm: ElementToMigrate, tmpl: string, offset: number
// includes the mandatory semicolon before as
const lbString = etm.hasLineBreaks ? '\n' : '';
const leadingSpace = etm.hasLineBreaks ? '' : ' ';
const condition = etm.attr.value;
// ngSwitchCases with no values results into `case ()` which isn't valid, based off empty
// value we add quotes instead of generating empty case
const condition = etm.attr.value.length === 0 ? `''` : etm.attr.value;
const originals = getOriginals(etm, tmpl, offset);

View file

@ -187,6 +187,32 @@ describe('control flow migration', () => {
);
});
it('should migrate an empty case', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
template: \`<div [ngSwitch]="testOpts">` +
`<p *ngSwitchCase="">Option 1</p>` +
`<p *ngSwitchCase="2">Option 2</p>` +
`</div>\`
})
class Comp {
testOpts = "1";
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
`template: \`<div>@switch (testOpts) { @case ('') { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>`,
);
});
it('should migrate multiple inline templates in the same file', async () => {
writeFile(
'/comp.ts',