© Spirit Boom Cat/Shutterstock.com
Infografik

Angular Testing


Jasmine/Karma

Characteristics

  • Standard for Angular apps (Angular CLI)

  • Jasmine provides test environment and matcher

  • Karma runs tests in real browser (Chrome, Firefox etc.)

Basic test for Angular component

import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SampleComponent } from './sample.component'; describe('SampleComponent', () => { let component: SampleComponent; let fixture: ComponentFixture<SampleComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SampleComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SampleComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create an instance', () => { expect(component).toBeTruthy(); }); });

Jest

Characteristics

  • Syntax initially inspired by Jasmine

  • Therefore, some parts are reusable

  • Tests can be run in Node.js environment with jsdom(emulates DOM in JavaScript)

  • Doesn’t provide full feature set of browser; missing APIs have to be emulated by mocking

  • Snapshot tests: compare rendered component with reference snapshot

Enable snapshot tests

it('should create the component', () => { const cmp = fixture .debugElement .nativeElement; expect(cmp).toMatchSnapshot(); });

Install dependencies

npm install -D jest jest-preset-angular @types/jest

Create “src/jestGlobal.ts”

import 'jest-preset-angular';

Edit files

“tsconfig.spec.json”

{ "compilerOptions": { ... "target": "es5", "module": "commonjs", "types": [ "jest", "node" ] ... } 

“package.json”

"jest": { "preset": "jest-preset-angular", "setupFilesAfterEnv": [ "<rootDir>/src/setupJest.ts" ], "testPathIgnorePatterns": [ "<rootDir>/src/test.ts" ], "globals": { "ts-jest": { "tsConfig": "<rootDir>/tsconfig.spec.json", "stringifyContentPathRegex": "\\.html$", "astTransformers": [ "jest-preset-angular/InlineHtmlStripStylesTransformer" ] } } } 
testpyramide_v2.eps_fmt1.jpg

Create mocks/spies with Jasmine

jasmine.createSpyObj('name', ['key']) const spy = jasmine.createSpy('name', originalFn) spy.and.returnValue('foo') spyOn(...).and.callFake(() => {})

Create mocks/spies with Jest

jest.fn(() => ({key: jest.fn()})) const mock = jest.fn() mock.mockReturnValue('bar') jest.spyOn(...).mockImplementation(() => {}) 
testpyramide_v2.eps_fmt1.jpg

Jasmine/Protractor

Characteristics

  • Standard for Angular apps (Angular CLI)

  • Jasmine provides test environment and assertion library

  • Protractor adresses Selenium (tool for browser automation)

  • Selenium performs clicks and keyboard input in browser l...

Exklusives Abo-Special

Angebote für Teams

Für Firmen haben wir individuelle Teamlizenzen. Wir erstellen Ihnen gerne ein passendes Angebot.

Das Library-Modell:
IP-Zugang

Das Company-Modell:
Domain-Zugang