user1261710
user1261710

Reputation: 2639

NativeScript - how to get unit tests to work properly?

I'm writing an app with NativeScript 6+ and Angular 8+.

I'm trying to write some unit tests and get them up and running.

I have read the documentation on unit testing: https://docs.nativescript.org/tooling/testing/testing

I followed the directions there for setting up the tests and using TestBed. My tests are not working and throwing errors.

Here is my repository: https://github.com/aubrey-fowler/NativeScriptUnitTests

Questions:

  1. The documentation only shows an example of how to write a test for a component. How do I write a test for a service? I also need to use TestBed for this because my service has dependency injection.
  2. My tests are throwing errors. Why and how can I fix them?

Errors:

no reachable hosts

on my Android phone

code snippet:

import { ItemsComponent } from '../app/item/items.component';

import {
    nsTestBedAfterEach,
    nsTestBedBeforeEach,
    nsTestBedRender
} from 'nativescript-angular/testing';

describe('ItemsComponent Test', () => {

    beforeEach(nsTestBedBeforeEach([ItemsComponent]));
    afterEach(nsTestBedAfterEach(false));

    it('should be defined', () => {

        nsTestBedRender(ItemsComponent).then((fixture) => {
            fixture.detectChanges();
            const component = fixture.componentInstance;
            expect(component).toBeTruthy;
        });

    });

});

Upvotes: 0

Views: 358

Answers (1)

Manoj
Manoj

Reputation: 21908

  1. I checked your repo, I'm unsure whether it's upto date as when I tried to run tns test [ios|android] it broke and I noticed none of the karma config files were existed in repo. I had to re-initialise test with tns test init and then it worked just fine.

  2. When you have dependencies for your component, you will have to pass the Service files in the providers array (Second parameter to nsTestBedBeforeEach function). If you want to test the service alone, you will have to create the instance yourself and run tests. If the service has dependencies, it's your responsibility to pass the dependencies in the constructor. Just the same as how you would do in Angular Web.

Upvotes: 1

Related Questions