2/8/2019 - 11:20 AM

Jasmine unit tests

ngDocs => https://angular.io/guide/testing


How to run specific test only

  • When using iit or ddescribe, you set focus only on this test/suite. FYI you should also look for fit and fdescribe as well (...and xit and xdescribe)


describe: optional, describe the entire unit testing class

it: must include it when writing isolated unit test

async: tell the test framework to wait until the return promise or observable is completed before treating the test as completed. when all async operations are completed the next test (if exists) is able to start executing

beforeEach: for creating new instances for another test to start from the beginning

TestBed: creates components instance, configure module, simulate module Access field/variable: fixture.componentInstance.some_variable_name OR if already instantiated then component.some_variable_name.


  • Do not re-configure TestBed after calling createComponent.
  • The createComponent method freezes the current TestBed definition, closing it to further configuration.

detectChanges: only triggered when an property change occurs inside a .ts file

fail: Can use when need to set test to red and show message e.g fail('should have failed with http error');

configureTestingModule: configures a “fake” module

toBe vs toEqual: toBe object(general) equality vs deep equality fixture.whenStable().then(() => {}); executes after all async operations are executed/finished tick() simulates the passage of time until all async operations above are finished. Must go with fakeAsync keyword, otherwise error will appear fixture.whenStable() vs tick(); They both do the same. tick() is more prudent to use because you have to give it (in the header of the test) a fakeAsync which means that everything is called synchronously inside the test. The code after the tick() method indicates that all code above has executed (async operations above) and that you can now proceed with testing the result of these above async operations. Fixture.whenStable() however can give a false positive if async() is omitted in the header of the test. Therefore the test will complete before fixture.whenStable executions.

A Spy: is a feature of Jasmine which lets you take an existing class, function, object and mock it in such a way that you can control what gets returned from functions.

Important: The subscribe() method takes a success (next) and fail (error) callback. Make sure you provide both callbacks so that you capture errors. Neglecting to do so produces an asynchronous uncaught observable error that the test runner will likely attribute to a completely different test. Я так зрозумів це треба робити коли тестуєш реальні HTTP req

const bannerDe: DebugElement = fixture.debugElement;
const bannerEl: HTMLElement = bannerDe.nativeElement;
Angular relies on the DebugElement abstraction to work safely across all supported platforms. Instead of creating an HTML element tree, 
Angular creates a DebugElement tree that wraps the native elements for the runtime platform. 
The nativeElement property unwraps the DebugElement and returns the platform-specific element object.
** The DebugElement has other methods and properties that are useful in tests, as you'll see elsewhere in this guide.

** The server-side renderer might not support the full HTML element API. If it doesn't support querySelector, the previous test could fail.
The DebugElement offers query methods that work for all supported platforms. import { By } from '@angular/platform-browser';
const bannerDe: DebugElement = fixture.debugElement;
const paragraphDe = bannerDe.query(By.css('p'));
const p: HTMLElement = paragraphDe.nativeElement;
expect(p.textContent).toEqual('banner works!')

 test doubles (stubs, fakes, spies, or mocks)
 Дублери (англ. Test double) — спеціалізовані методи чи об'єкти, які використовуються при тестуванні систем, 
 в яких виникає необхідність взаємодії з зовнішніми об'єктами, наприклад: бази даних, файлова система,
 мережеве з'єднання та тощо. При цьому дублер повинен реалізувати інтерфейс зовнішнього об'єкту та відповідати
 всім вимогам, які висуваються до реального об'єкта.