How to implement unit tests in NativeScript using TestBed and Jasmine?
Asked 07 September, 2021
Viewed 1K times
  • 56
Votes

I'm setting up a NativeScript-Angular project, and would like to implement unit tests using Jasmine-Karma in order to test my components using css selectors. How can I setup a simple unit test (beyond the sample test provided on the official repository) for a simple component?

This is for a new project using NativeScript CLI 6.0 with Android API level 28.

I have tried using the regular Angular TestBed which is claimed to be supported on this blog post: https://www.nativescript.org/blog/announcing-the-nativescript-4.1-release

I have also tried following their working tests on the official nativescript-angular repository: https://github.com/NativeScript/nativescript-angular/tree/master/tests

Either way I seem to be doing something wrong when I try to do my own implementation because I get the following errors:
Uncaught Error: Zone already loaded
TypeError: Cannot read property 'injector' of null
TypeError: Cannot read property 'getComponentFromError' of null
TypeError: Cannot read property 'currentPage' of undefined

Has anyone managed to get TestBed unit tests working in NativeScript with Jasmine-Karma?

test-main.ts

import "nativescript-angular/zone-js/testing.jasmine";
import { nsTestBedInit } from "nativescript-angular/testing";
nsTestBedInit();

example.ts

import { ItemsComponent } from '~/app/item/items.component';
import { By } from '@angular/platform-browser';
import { nsTestBedBeforeEach, nsTestBedAfterEach, nsTestBedRender } from 'nativescript-angular/testing';

describe('item-detail-component', () => {
  beforeEach(nsTestBedBeforeEach(
    [ItemsComponent]
  ));
  afterEach(nsTestBedAfterEach());

  it(`should contain items`, () => {
    return nsTestBedRender(ItemsComponent).then((fixture) => {
      fixture.detectChanges();
      const list = fixture.debugElement.query(By.css('.list-group'));

      expect(list).toBeDefined();
    });
  })
});

I am expecting to be able to run the test without getting any errors.

I have included two repos for each test implementation.
Steps to reproduce:
1. Download repo
2. yarn install
3. tns test android

https://github.com/gsavchenko/nativescript-ns-testbed

update

for anyone else wondering how to further test their front-end using end to end tests it seems like appium is the go to https://docs.nativescript.org/plugins/ui-tests

3 Answer