NativeScript - how to get unit tests to work properly?

折月煮酒 提交于 2020-03-25 18:24:12

问题


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;
        });

    });

});

回答1:


  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.



来源:https://stackoverflow.com/questions/60737734/nativescript-zoneawareerror-when-running-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!