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 3 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
69 changes: 63 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,46 @@ 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 === true ||
(properties?.detectChangesOnRender === undefined && detectChangesOnRender === true)
Copy link
Member

Choose a reason for hiding this comment

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

Do you think we need this check to use the existing config?
I didn't think of it, and I assumed it would only use the property passed to this function.

Copy link
Contributor Author

@shaman-apprentice shaman-apprentice Mar 7, 2023

Choose a reason for hiding this comment

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

My first intuition is to respect the initial flag from render unless explicit overwritten in rerender. But my personal goal is to never use any of those two flags - so I have no real opinion here ;) Should I only check for properties?.detectChangesOnRender === true?

Copy link
Member

Choose a reason for hiding this comment

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

Yea that's my personal goal as well 😅
I would only check for the properties if you don't mind.

Copy link
Contributor Author

@shaman-apprentice shaman-apprentice Mar 10, 2023

Choose a reason for hiding this comment

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

done with d218907

) {
fixture.componentRef.injector.get(ChangeDetectorRef).detectChanges();
}
};

const changeInput = (changedInputProperties: Partial<SutType>) => {
Expand Down Expand Up @@ -360,6 +392,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
69 changes: 65 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,59 @@ 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,
},
});
});

describe('detectChangesOnRender', () => {
test('change detection gets not called if disabled within render', async () => {
const { rerender, detectChanges } = await render(FixtureComponent, { detectChangesOnRender: false });
detectChanges();
expect(screen.getByText('Sarah')).toBeInTheDocument();

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

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

test('change detection gets called if disabled within render but enabled within rerender', async () => {
const { rerender, detectChanges } = await render(FixtureComponent, { detectChangesOnRender: false });
detectChanges();
expect(screen.getByText('Sarah')).toBeInTheDocument();

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

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

test('change detection gets not called if disabled within rerender', 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();
});
});