Skip to content

training360-trainings/Angular-im-2023-unit-testing

Repository files navigation

Angular Unit Testing

Start

  • npm run dev

Intro

Smart and dump components

import { ForbiddenComponent } from "../app/page/forbidden/forbidden.component";
"test:01": "ng test --include=**/tests/forbidden.component.spec.ts",
"test": "ng test --include=**/tests/*.spec.ts --browsers ChromeHeadless --watch false",
  • commands:
  • npm run test:01
  • npm test

HTML elements

it("should have a h1", () => {
  const h1 = fixture.nativeElement.querySelector("h1");
  expect(h1).toBeTruthy();
  expect(h1.textContent).toContain("Forbidden");
});

it('h1 content should be "forbidden"', () => {
  const h1 = fixture.nativeElement.querySelector("h1");
  expect(h1.textContent).toMatch(/forbidden/i);
});
  • command: npm test

Testing a method call

onHomeClick() {
  console.log('home');
  }
<h2 style="text-align: center; margin-top: 1em;">
  <button (click)="onHomeClick()">Go to the home page</button>
</h2>
it("should have a button to the home page", () => {
  const button = fixture.nativeElement.querySelector("button");
  expect(button).toBeTruthy();
});

it('button text should be "go to the home page"', () => {
  const button = fixture.nativeElement.querySelector("button");
  expect(button.textContent).toMatch(/go to the home page/i);
});

it("click on button shuld be trigger the onHomeClick method", () => {
  const button = fixture.nativeElement.querySelector("button");
  spyOn(component, "onHomeClick");

  button.click();
  expect(component.onHomeClick).toHaveBeenCalled();
});

Testing and Dependency Injection

  • CustomerEditor: copy to
  • fix component path:
  • import { CustomerEditorComponent } from '../app/page/customer-editor/customer-editor.component';
  • add imports:
HttpClientTestingModule,
BrowserAnimationsModule,
providers: [
  {
    provide: CustomerService,
    useClass: CustomerServiceMock,
  },
],
it("customer should be the first customer in the list", () => {
  component.id = 1;
  component.ngOnInit();

  setTimeout(() => {
    expect(component.customer()).toBe(component.store.list()[0]);
  });
});

Form testing

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors