Skip to content

Changing a form input doesn't make the form touched or dirty #36

@jdhines

Description

@jdhines

I can't for the life of me figure out how to get this test to pass, even though it works from the running application.

I have a form which starts in pristine condition, and a save button which is disabled via:
<button type="submit" [disabled]="myForm.invalid || myForm.pristine" (click)="openSaveConfirmation()" title="Save changes">Save</button>

My test calls a setup function which just calls render and returns that whole object, and then does what it needs to to get mock data in the form. That's all working fine.

However, in my test, no matter how I've tried changing the input, it doesn't make the form not pristine, (i.e. doesn't set touched or dirty to true, and hence only in the test, the button is disabled.

I don't think I should have to call fixture.detectChanges() because I'm using fireEvent and the functions returned from render but please correct me if I'm misunderstanding.

The test (other things I've tried combinations of are commented out). The final 2 assertions fail.

test('Save button should be enabled after making a change', async () => {
  const {
    container,
    fixture,
    getByText,
    getByLabelText,
    getByDisplayValue,
  } = await setupWithDataLoaded();
  fixture.detectChanges(); //have to do this or else the test doesn't detect that data has loaded even though the setup function only uses destructured functions from render()
 
  // fixture.componentInstance.myForm.markAsTouched();

  const lastNameInput = <HTMLInputElement>getByLabelText(/last name/i);

  expect(lastNameInput).toHaveValue('Smith'); // ✓ passes
  // lastNameInput.focus();
  fireEvent.change(lastNameInput, { target: { value: 'Wilson' } });
  expect(<HTMLInputElement>getByLabelText(/last name/i)).toHaveValue('Wilson'); // ✓ passes

  // fireEvent.keyDown(document.activeElement || document.body);
  // fixture.detectChanges();
  expect(fixture.componentInstance.myEduForm.valid).toBeTruthy(); // ✓ passes
  expect(fixture.componentInstance.myEduForm.touched).toBeTruthy(); // 𝙭 fails
  expect(getByText('Save')).toBeEnabled(); // 𝙭 fails (because it can't tell the form is touched I guess) 
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions