question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

karma in watch mode broken form tests when refresh

See original GitHub issue

I try test a form required, the first time test pass normal, but when I change the file and karma refresh the tests all tests in form broken

app.component.ts

import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <form [formGroup]="form">
      <input type="text" formControlName="name" aria-label="name" />
      <div *ngIf="name.invalid && name.touched">
        <p aria-label="error name" *ngIf="name.errors?.['required']">
          Campo obrigatorio
        </p>
      </div>
    </form>
  `,
})
export class AppComponent {
  form: FormGroup = this.fb.group({
    name: ['', [Validators.required]],
  });

  constructor(private fb: FormBuilder) {}

  get name(): FormControl {
    return this.form.get('name') as FormControl;
  }
}

**app.component.testing-library.spec.ts **

import { render, screen } from '@testing-library/angular';

import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import userEvent from '@testing-library/user-event';

describe('Testing library Form', () => {
  const { getByLabelText, getByText } = screen;
  const setup = () => {
    return render(AppComponent, {
      imports: [ReactiveFormsModule],
    });
  };

  it('should render a component with testing library', async () => {
    await setup();

    expect(getByLabelText('name')).toBeInTheDocument();
  });

  it('should show erro message required with testing library', async () => {
    const { fixture } = await setup();
    fixture.detectChanges();

    const input = getByLabelText('name');

    await userEvent.click(input);
    await userEvent.tab();

    console.log('COMMENT TO REFRESH');

    expect(getByText('Campo obrigatorio')).toBeInTheDocument();
  });
});

At first time the testing pass:

Screenshot from 2022-07-25 13-35-38

But when I change some file, this happen:

Screenshot from 2022-07-25 13-36-58

When I refresh with F5, the tests back to pass:

Screenshot from 2022-07-25 13-38-01 Screenshot from 2022-07-25 13-38-11

I thought that was karma or karma-launch, but if I test with normal library angular this work normally app.component.ts

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { AppComponent } from './app.component';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

const dispatchFakeEvent = (
  element: EventTarget,
  type: string,
  bubbles: boolean = false
): void => {
  const event = document.createEvent('event');
  event.initEvent(type, bubbles, false);
  element.dispatchEvent(event);
};

const markFieldAsTouched = (element: DebugElement) => {
  dispatchFakeEvent(element.nativeElement, 'blur');
};

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;

  const setup = async () => {
    await TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [ReactiveFormsModule],
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  };

  it('should render a component with testing angular', async () => {
    await setup();

    expect(component).toBeTruthy();
  });

  it('should show erro message required with testing angular', async () => {
    await setup();

    const appComponent: DebugElement = fixture.debugElement;

    const input = appComponent.query(By.css('input'));
    markFieldAsTouched(input);

    fixture.detectChanges();

    const error = appComponent.query(By.css('p')).nativeElement;

    expect(error).toBeTruthy();
    expect(error).toHaveTextContent('Campo obrigatorio');
  });
});

the env in my github: https://github.com/jadir-junior/angular-karma-and-testing-library

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
rothsandrocommented, Jul 28, 2022

The browser needs to be focused, see https://github.com/testing-library/user-event/issues/553

1reaction
timdeschryvercommented, Jul 26, 2022

@jadir-junior thanks again. It seems like it doesn’t blur correctly, you could use fireEvent.blur for now which should work:

  it('should show error message required with testing library', async () => {
    await setup();

    const input = getByLabelText('name');
    fireEvent.blur(input);
    expect(screen.getByText('Campo obrigatorio')).toBeInTheDocument();
  });
Read more comments on GitHub >

github_iconTop Results From Across the Web

clearContext:true and watch mode causes "Some of your tests ...
I'm running karma in watch mode along with clearContext: true (which in fact was ... self.error('Some of your tests did a full page...
Read more >
karma test runner not running any tests - Stack Overflow
Under karma.config.js , set either singleRun or autoWatch to true . In your case both of them are set to false, hence karma...
Read more >
Karma | IntelliJ IDEA Documentation - JetBrains
Karma executes tests against your application running in a real browser, which ensures correctness and trustworthiness of test results. IntelliJ ...
Read more >
Configuration File - Karma
Description: Enable or disable watching files and executing the tests whenever one of these files changes. autoWatchBatchDelay #. Type: Number. Default: 250.
Read more >
NG0100: Expression has changed after it was checked - Angular
In development mode, Angular performs an additional check after each change detection run, to ensure the bindings haven't changed. This catches errors where ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found