Skip to content

Commit

Permalink
fix: check that changes are defined
Browse files Browse the repository at this point in the history
It can easily happen that items are undefined as a change when
ngOnChanges is called in GalleryComponent. This is a deficiency of the
Angular's types that this is not checked, and it slipped through my test
suite as well.

So I created a stricter type that will keep the possibility of changes
being undefined in check and reorganized the test so that the ngOnChanges
with undefined `items` change is checked as well.
  • Loading branch information
daelmaak committed Dec 17, 2023
1 parent 7cc9e84 commit ebdc346
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ describe('GalleryComponent', () => {

it('should handle empty items input in looping mode', () => {
componentRef.setInput('items', undefined);
fixture.detectChanges();

componentRef.setInput('loop', true);
fixture.detectChanges();

Expand Down
6 changes: 3 additions & 3 deletions libs/gallery/src/lib/components/gallery/gallery.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
Input,
OnChanges,
Output,
SimpleChanges,
TemplateRef,
ViewChild,
} from '@angular/core';
Expand All @@ -27,6 +26,7 @@ import {
VerticalOrientation,
} from '../../core';
import { defaultAria } from '../../core/aria';
import { StrictSimpleChanges } from '../../core/ng';
import { ThumbsComponent } from '../thumbs/thumbs.component';
import { ViewerComponent } from '../viewer/viewer.component';

Expand Down Expand Up @@ -191,8 +191,8 @@ export class GalleryComponent implements OnChanges {
: OrientationFlag.VERTICAL;
}

ngOnChanges({ items }: SimpleChanges) {
if (!items.currentValue) {
ngOnChanges({ items }: StrictSimpleChanges<GalleryComponent>) {
if (!items?.currentValue) {
this.items = [];
}
}
Expand Down
6 changes: 5 additions & 1 deletion libs/gallery/src/lib/core/ng.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { ComponentRef } from '@angular/core';
import { ComponentRef, SimpleChange, SimpleChanges } from '@angular/core';

export interface StrictComponentRef<C> extends ComponentRef<C> {
// `& string` because otherwise keyof would return string | number
setInput(name: keyof C & string, value: unknown): void;
}

export type StrictSimpleChanges<T> = SimpleChanges & {
[propName in keyof T]: SimpleChange | undefined;
};

0 comments on commit ebdc346

Please sign in to comment.