Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support ngOnChanges with correct simpleChange object within rerender #366

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions projects/testing-library/src/lib/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ export interface RenderResult<ComponentType, WrapperType = ComponentType> extend
/**
* @description
* Re-render the same component with different properties.
* This creates a new instance of the component.
* Properties not passed in again are removed.
*/
rerender: (
properties?: Pick<
RenderTemplateOptions<ComponentType>,
'componentProperties' | 'componentInputs' | 'componentOutputs'
'componentProperties' | 'componentInputs' | 'componentOutputs' | 'detectChangesOnRender'
>,
) => Promise<void>;
/**
Expand Down
66 changes: 60 additions & 6 deletions projects/testing-library/src/lib/testing-library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,43 @@ export async function render<SutType, WrapperType = SutType>(

await renderFixture(componentProperties, componentInputs, componentOutputs);

let renderedPropKeys = Object.keys(componentProperties);
let renderedInputKeys = Object.keys(componentInputs);
let renderedOutputKeys = Object.keys(componentOutputs);
const rerender = async (
properties?: Pick<RenderTemplateOptions<SutType>, 'componentProperties' | 'componentInputs' | 'componentOutputs'>,
properties?: Pick<
RenderTemplateOptions<SutType>,
'componentProperties' | 'componentInputs' | 'componentOutputs' | 'detectChangesOnRender'
>,
) => {
await renderFixture(
properties?.componentProperties ?? {},
properties?.componentInputs ?? {},
properties?.componentOutputs ?? {},
);
const newComponentInputs = properties?.componentInputs ?? {};
for (const inputKey of renderedInputKeys) {
if (!Object.prototype.hasOwnProperty.call(newComponentInputs, inputKey)) {
delete (fixture.componentInstance as any)[inputKey];
}
}
setComponentInputs(fixture, newComponentInputs);
renderedInputKeys = Object.keys(newComponentInputs);

const newComponentOutputs = properties?.componentOutputs ?? {};
for (const outputKey of renderedOutputKeys) {
if (!Object.prototype.hasOwnProperty.call(newComponentOutputs, outputKey)) {
delete (fixture.componentInstance as any)[outputKey];
}
}
setComponentOutputs(fixture, newComponentOutputs);
renderedOutputKeys = Object.keys(newComponentOutputs);

const newComponentProps = properties?.componentProperties ?? {};
const changes = updateProps(fixture, renderedPropKeys, newComponentProps);
if (hasOnChangesHook(fixture.componentInstance)) {
fixture.componentInstance.ngOnChanges(changes);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While looking at this PR I think we should also include componentInputs to ngOnChanges.
We don't do this with the current behavior, but I think that that should be added (in a later PR).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. If this PR would be released without it, and I would use componentInputs in rerender, I probably would create a bug for it. If you agree I would already add it in this PR.

}
renderedPropKeys = Object.keys(newComponentProps);

if (properties?.detectChangesOnRender !== false) {
fixture.componentRef.injector.get(ChangeDetectorRef).detectChanges();
}
};

const changeInput = (changedInputProperties: Partial<SutType>) => {
Expand Down Expand Up @@ -360,6 +389,31 @@ function getChangesObj(oldProps: Record<string, any> | null, newProps: Record<st
);
}

function updateProps<SutType>(
fixture: ComponentFixture<SutType>,
prevRenderedPropsKeys: string[],
newProps: Record<string, any>,
) {
const componentInstance = fixture.componentInstance as Record<string, any>;
const simpleChanges: SimpleChanges = {};

for (const key of prevRenderedPropsKeys) {
if (!Object.prototype.hasOwnProperty.call(newProps, key)) {
simpleChanges[key] = new SimpleChange(componentInstance[key], undefined, false);
delete componentInstance[key];
}
}

for (const [key, value] of Object.entries(newProps)) {
if (value !== componentInstance[key]) {
simpleChanges[key] = new SimpleChange(componentInstance[key], value, false);
}
}
setComponentProperties(fixture, newProps);

return simpleChanges;
}

function addAutoDeclarations<SutType>(
sut: Type<SutType> | string,
{
Expand Down
43 changes: 39 additions & 4 deletions projects/testing-library/tests/rerender.spec.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import { Component, Input } from '@angular/core';
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { render, screen } from '../src/public_api';

let ngOnChangesSpy: jest.Mock;
@Component({
selector: 'atl-fixture',
template: ` {{ firstName }} {{ lastName }} `,
})
class FixtureComponent {
class FixtureComponent implements OnChanges {
@Input() firstName = 'Sarah';
@Input() lastName?: string;
ngOnChanges(changes: SimpleChanges): void {
ngOnChangesSpy(changes);
}
}

beforeEach(() => {
ngOnChangesSpy = jest.fn();
});

test('rerenders the component with updated props', async () => {
const { rerender } = await render(FixtureComponent);
expect(screen.getByText('Sarah')).toBeInTheDocument();
Expand Down Expand Up @@ -54,6 +62,33 @@ test('rerenders the component with updated props and resets other props', async
const firstName2 = 'Chris';
await rerender({ componentProperties: { firstName: firstName2 } });

expect(screen.queryByText(`${firstName2} ${lastName}`)).not.toBeInTheDocument();
expect(screen.queryByText(`${firstName} ${lastName}`)).not.toBeInTheDocument();
expect(screen.getByText(firstName2)).toBeInTheDocument();
expect(screen.queryByText(firstName)).not.toBeInTheDocument();
expect(screen.queryByText(lastName)).not.toBeInTheDocument();

expect(ngOnChangesSpy).toHaveBeenCalledTimes(2); // one time initially and one time for rerender
const rerenderedChanges = ngOnChangesSpy.mock.calls[1][0] as SimpleChanges;
expect(rerenderedChanges).toEqual({
lastName: {
previousValue: 'Peeters',
currentValue: undefined,
firstChange: false,
},
firstName: {
previousValue: 'Mark',
currentValue: 'Chris',
firstChange: false,
},
});
});

test('change detection gets not called if `detectChangesOnRender` is set to false', async () => {
const { rerender } = await render(FixtureComponent);
expect(screen.getByText('Sarah')).toBeInTheDocument();

const firstName = 'Mark';
await rerender({ componentInputs: { firstName }, detectChangesOnRender: false });

expect(screen.getByText('Sarah')).toBeInTheDocument();
expect(screen.queryByText(firstName)).not.toBeInTheDocument();
});