【问题标题】:NativeScript - how to get unit tests to work properly?NativeScript - 如何让单元测试正常工作?
【发布时间】:2020-03-14 03:18:16
【问题描述】:

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

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

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

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

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

问题:

  1. 文档仅显示了如何编写测试的示例 零件。如何为服务编写测试?我也需要使用 TestBed 因为我的服务有依赖注入。
  2. 我的测试抛出错误。为什么以及如何解决它们?

错误:

no reachable hosts

在我的安卓手机上

代码sn-p:

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

    });

});

【问题讨论】:

    标签: angular unit-testing nativescript


    【解决方案1】:
    1. 我检查了你的 repo,我不确定它是否是最新的,因为当我尝试运行 tns test [ios|android] 时它坏了,我注意到 repo 中不存在任何 karma 配置文件。我不得不使用 tns test init 重新初始化测试,然后它就可以正常工作了。

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

    【讨论】:

    • 2.我们能否将 TestBed 用于具有 NativeScript 依赖项的服务?
    • 1.它仍然对我不起作用。我对此提出了一个新问题:stackoverflow.com/questions/60737734/…
    • 2.你也许可以做到,但你不必这样做。但是,如果您愿意,可以随时查看官方文档以获取示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多