首页 > 解决方案 > NativeScript - 如何让单元测试正常工作?

问题描述

我正在使用 NativeScript 6+ 和 Angular 8+ 编写应用程序。

我正在尝试编写一些单元测试并让它们启动并运行。

我已阅读有关单元测试的文档: https ://docs.nativescript.org/tooling/testing/testing

我按照那里的说明设置测试和使用 TestBed。我的测试不工作并抛出错误。

这是我的存储库:https ://github.com/aubrey-fowler/NativeScriptUnitTests

问题:

  1. 该文档仅显示了如何为组件编写测试的示例。如何为服务编写测试?我还需要为此使用 TestBed,因为我的服务具有依赖注入。
  2. 我的测试抛出错误。为什么以及如何修复它们?

错误:

no reachable hosts

在我的安卓手机上

代码片段:

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

    });

});

标签: angularunit-testingnativescript

解决方案


  1. 我检查了您的存储库,我不确定它是否是最新的,因为当我尝试运行tns test [ios|android]它时它坏了,我注意到存储库中不存在任何业力配置文件。我不得不重新初始化测试,tns test init然后它工作得很好。

  2. 当您的组件具有依赖项时,您必须在提供程序数组中传递服务文件(nsTestBedBeforeEach函数的第二个参数)。如果您想单独测试服务,则必须自己创建实例并运行测试。如果服务具有依赖项,则您有责任在构造函数中传递依赖项。就像你在Angular Web中所做的一样。


推荐阅读