Skip to content

test: enhance example to verify pre-set form values on a Material sel… #276

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

Merged
merged 3 commits into from
Jan 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
39 changes: 38 additions & 1 deletion apps/example-app/src/app/examples/04-forms-with-material.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import userEvent from '@testing-library/user-event';

import { MaterialModule } from '../material.module';
import { MaterialFormsComponent } from './04-forms-with-material';
import { FormBuilder, Validators } from "@angular/forms";
import { By } from "@angular/platform-browser";


test('is possible to fill in a form and verify error messages (with the help of jest-dom https://testing-library.com/docs/ecosystem-jest-dom)', async () => {
const { fixture } = await render(MaterialFormsComponent, {
Expand Down Expand Up @@ -37,12 +40,46 @@ test('is possible to fill in a form and verify error messages (with the help of

expect(nameControl).toHaveValue('Tim');
expect(scoreControl).toHaveValue(7);
expect(colorControl).toHaveTextContent('Green');

const form = screen.getByRole('form');
expect(form).toHaveFormValues({
name: 'Tim',
score: 7,
});

expect((fixture.componentInstance as MaterialFormsComponent).form?.get('color')?.value).toBe('G');
});

test('is should show pre-set form values', async () => {
const formBuilder = new FormBuilder();

const { fixture, detectChanges } = await render(MaterialFormsComponent, {
imports: [MaterialModule],
componentProperties: {
Copy link
Member

Choose a reason for hiding this comment

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

Thanks for enhancing this example.
I would like to change a few things, the most important one to not overwrite the form.
Because this also overwrites the validators, which can be problematic if requirements change.

It's also sufficient to invoke a change detection cycle (we don't need to click on the trigger).

Thoughts?

  const { fixture, detectChanges } = await render(MaterialFormsComponent, {
    imports: [MaterialModule],
  });

  fixture.componentInstance.form.setValue({
    name: 'Max',
    score: 4,
    color: 'B'
  })
  detectChanges();
  
  const nameControl = screen.getByLabelText(/name/i);
  const scoreControl = screen.getByRole('spinbutton', { name: /score/i });
  const colorControl = screen.getByRole('combobox', { name: /color/i });

  expect(nameControl).toHaveValue('Max');
  expect(scoreControl).toHaveValue(4);
  expect(colorControl).toHaveTextContent('Blue');

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@timdeschryver yes, that is indeed a very good point. I adapted it.

Copy link
Member

Choose a reason for hiding this comment

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

While this works, I'm thinking if we can do something about this to provide a better experience.
Not sure if this is better though 😅
If you have an idea, feel free to drop it here.

const { fixture } = render(Component);
// this would be new and invokes a CD cycle 
invoke(() => {
  fixture.componentInstance.form.setValue();
})

Copy link
Contributor Author

@mleimer mleimer Jan 5, 2022

Choose a reason for hiding this comment

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

@timdeschryver If we had to update the form values from within the test, this might be an option.

However, in a scenario where one uses custom written Angular components for different form fields, there is most likely a formControl being passed into it through its input properties. If we now follow the example from https://github.com/testing-library/angular-testing-library/blob/main/apps/example-app/src/app/examples/02-input-output.spec.ts#L10 how to pass input properties, one would not think of having to call detectChanges() to validate any pre-set value within the formControl.

Maybe we should consider adding a test scenario where one passes a formControl into the test component?

Copy link
Member

Choose a reason for hiding this comment

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

Those examples are based on "real-world" scenarios.
I didn't had the need (yet) to pass form controls to child components - and editing the code just for the tests doesn't feel right. The same problem also applies when validators are added to the control.

For now, I think this example shows a user how to do it the best way.
We can revisit and modify this later if we can think of a better solution.

form: formBuilder.group({
name: ['Max', Validators.required],
score: [4, [Validators.min(1), Validators.max(10)]],
color: ['B', Validators.required],
}),
},
});

const nameControl = screen.getByLabelText(/name/i);
const scoreControl = screen.getByRole('spinbutton', { name: /score/i });
const colorControl = screen.getByRole('combobox', { name: /color/i });

expect(nameControl).toHaveValue('Max');
expect(scoreControl).toHaveValue(4);

fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement.click();
detectChanges();
expect(colorControl).toHaveTextContent('Blue');

const form = screen.getByRole('form');
expect(form).toHaveFormValues({
name: 'Max',
score: 4,
});

expect((fixture.componentInstance as MaterialFormsComponent).form?.get('color')?.value).toBe('B');
});
10 changes: 9 additions & 1 deletion apps/example-app/src/app/examples/04-forms-with-material.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ import { FormBuilder, Validators } from '@angular/forms';

<mat-form-field>
<mat-select placeholder="Color" name="color" formControlName="color">
<mat-select-trigger>
{{ colorControlDisplayValue }}
</mat-select-trigger>
<mat-option value="">---</mat-option>
<mat-option *ngFor="let color of colors" [value]="color.id">{{ color.value }}</mat-option>
</mat-select>
Expand Down Expand Up @@ -60,11 +63,16 @@ export class MaterialFormsComponent {
form = this.formBuilder.group({
name: ['', Validators.required],
score: [0, [Validators.min(1), Validators.max(10)]],
color: ['', Validators.required],
color: [null, Validators.required],
});

constructor(private formBuilder: FormBuilder) {}

get colorControlDisplayValue(): string | undefined {
const selectedId = this.form.get('color')?.value;
return this.colors.filter(color => color.id === selectedId)[0]?.value;
}

get formErrors() {
return Object.keys(this.form.controls)
.map((formKey) => {
Expand Down