【问题标题】:Can we use TestBed for services with NativeScript?我们可以将 TestBed 用于带有 NativeScript 的服务吗?
【发布时间】:2020-03-18 10:28:11
【问题描述】:

我正在使用 NativeScript 6+ 和 Angular 8+ 编写应用程序。 我正在尝试编写一些单元测试并让它们启动并运行。 我已阅读有关单元测试的文档:https://docs.nativescript.org/tooling/testing/testing 我已经使用普通服务启动并运行了一些单元测试。 例如

import { ItemService } from '../app/item/item.service';

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

    let service: ItemService;

    beforeEach(() => { service = new ItemService(); });

    it('should be defined',() => {
        expect(service).toBeTruthy();
    });

    it('should have its functions defined',() => {
        expect(service.getItems).toBeTruthy();
        expect(service.getItem).toBeTruthy();
    });

});

我看到我们可以通过在构造函数中实例化它们以及使用模拟服务来测试具有依赖关系的服务。 https://angular.io/guide/testing#service-tests

是否可以在 NativeScript 中将 TestBed 用于我们的服务?如果是这样,你能提供一个如何做到这一点的例子吗?

【问题讨论】:

  • 如果您继续阅读相同的文档,这里有一些示例说明您如何使用依赖项测试服务,甚至使用 TestBed。你已经试过了吗?如果是,请描述您面临的问题。
  • @Manoj 在文档中哪里显示了 TestBed 的示例?你是说 Angular 文档吗?你能用 NativeScript 的例子写一个答案吗?如果可以使用 Angular TestBed,为什么还要配置 NS TestBed?能详细点吗?
  • NS 在 Angular TestBed 之上几乎没有什么功能,因为默认情况下 TestBed 是为浏览器设计的。我将尝试运行测试并更新答案

标签: angular unit-testing nativescript karma-jasmine


【解决方案1】:

将服务作为第二个参数传递给nsTestBedBeforeEach,然后使用TestBed 获取实例

import { TestBed } from "@angular/core/testing";
import { nsTestBedBeforeEach } from "nativescript-angular/testing";

import { ItemService } from "../app/item/item.service";

describe("ItemsService Test", () => {
    let service: ItemService;

    beforeEach(nsTestBedBeforeEach([], [ItemService]));

    it("should use ItemService", () => {
        service = TestBed.get(ItemService);
        expect(service.getItems).toBeTruthy();
        expect(service.getItem).toBeTruthy();
    });
});

【讨论】:

    【解决方案2】:
    var mainViewModel = require("../main-view-model"); //Require the main view model to expose the functionality inside it.
    
    describe("Hello World Sample Test:", function() {
      it("Check counter.", function() {
        expect(mainViewModel.createViewModel().counter).toEqual(42); //Check if the counter equals 42.
      });
      it("Check message.", function () {
        expect(mainViewModel.createViewModel().message).toBe("42 taps left"); //Check if the message is "42 taps left".
      });
    });
    

    【讨论】:

    • 您好,感谢您的回答。我正在使用 Angular 和 NS。你有适用于 Angular 的解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 2021-11-02
    • 2016-01-20
    • 1970-01-01
    相关资源
    最近更新 更多