【问题标题】:Accessing nativeElement of a custom angular HTML tag访问自定义角度 HTML 标记的 nativeElement
【发布时间】:2018-05-30 05:54:31
【问题描述】:

我正在使用以下代码在我的应用程序中为第 3 方滑块 (https://www.npmjs.com/package/angular2-ui-switch) 编写 Angular Jasmine 单元测试:

HTML:

<ui-switch id="EditSwitch" name="EditSwitch" (change)="togglePageState()"></ui-switch>

Typescript .spec 文件:

  it('clicking slider changes page state', async () => {
    fixture.detectChanges();

    spyOn(component, 'togglePageState');

    let slider = fixture.debugElement.query(By.css('#EditSwitch')).nativeElement;
    slider.change();
    fixture.whenStable().then(() => {
      expect(component.togglePageState).toHaveBeenCalled();
    });

  });

但是,每当我运行单元测试时,都会出现错误:

HeadlessChrome 0.0.0 (Windows 10 0.0.0) Test Configuration Component clicking slider changes page state FAILED
        Failed: Cannot read property 'nativeElement' of null
        TypeError: Cannot read property 'nativeElement' of null
            at Object.<anonymous> src/app/configuration/configuration.component.spec.ts:105:71)
            at step (http://localhost:9876/_karma_webpack_/main.bundle.js:89:23)
            at Object.next (http://localhost:9876/_karma_webpack_/main.bundle.js:70:53)
            at http://localhost:9876/_karma_webpack_/main.bundle.js:64:71
            at new ZoneAwarePromise node_modules/zone.js/dist/zone.js:891:1)
            at webpackJsonp../src/app/configuration/configuration.component.spec.ts.__awaiter (http://localhost:9876/_karma_webpack_/main.bundle.js:60:12)
            at UserContext.<anonymous> src/app/configuration/configuration.component.spec.ts:100:52)
            at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
            at ProxyZoneSpec.webpackJsonp../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:288:1)
            at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:387:1)
.......

我相信这是因为我使用了自定义 HTML 标签“ui-switch”。

如何在这个自定义的“ui-switch”HTML 标记上使用 nativeElement?有没有我需要使用的替代方法来代替 nativeElement?

谢谢!

【问题讨论】:

  • 这是不可能的,因为 Angular ui-switch 不包含在运行时的 html 代码中。有html模板代码。

标签: javascript angular unit-testing typescript jasmine


【解决方案1】:

ui-switch 在运行时会在其中嵌入一些其他标签。您应该使用其唯一的类或 id 检查这些 nativeElement。

无法直接检查ui-switch。

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 2017-07-11
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2020-01-26
    相关资源
    最近更新 更多