Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active June 20, 2023 17:29
Show Gist options
  • Save ernestlv/9153ee6a7529b5a0442b2118a6f4278c to your computer and use it in GitHub Desktop.
Save ernestlv/9153ee6a7529b5a0442b2118a6f4278c to your computer and use it in GitHub Desktop.
#Angular component test with change detection, click event and input validation
import { DebugElement } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from "@angular/platform-browser"; // predicates for browser environment
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [ReactiveFormsModule],
declarations: [AppComponent]
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'ng-app'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('ng-app'); // component prop
});
it('should render render header', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges(); // triggers change detection updates component state
const domElement = fixture.nativeElement as HTMLElement; // shortcut for fixture.debugElement.nativeElement
expect(domElement.querySelector('h1')?.textContent).toContain('Forms');
});
it('should response to click button', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges(); //angular change detection
const debugEle: DebugElement = fixture.debugElement;
const debugButton = debugEle.query( By.css("button.first-button") ); // platform agnostic element wrapper & query
debugButton.triggerEventHandler("click", null);
const debugInput = debugEle.query( By.css("input.first-input") ); // input element wrapper
expect(debugInput.nativeElement.value).not.toEqual(''); // access DOM element
});
});
@ernestlv
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment