【问题标题】:Karma + Jasmine - Default unit test "it should create" failing with error "Uncaught TypeError: Cannot read property 'nativeElement' of undefined"Karma + Jasmine - 默认单元测试“它应该创建”失败并出现错误“Uncaught TypeError: Cannot read property 'nativeElement' of undefined”
【发布时间】:2021-10-11 16:53:18
【问题描述】:

我有一个非常简单的单元测试——由 Angular 自动生成的测试。

import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { CtaSecondaryComponent } from './cta-secondary.component';

describe('CtaSecondaryComponent', () => {
  let component: CtaSecondaryComponent;
  let fixture: ComponentFixture<CtaSecondaryComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CtaSecondaryComponent ],
      schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CtaSecondaryComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

大约 50% 的时间我会收到错误(即测试没有变化——有时它会失败,有时它会通过):

    Uncaught TypeError: Cannot read property 'nativeElement' of undefined thrown

据我所知,这个组件中的任何地方都没有对 nativeElement 的引用。事实上,在整个项目中的任何地方都没有对 nativeElement 的引用。我在网上找不到其他有此问题的人。谁能提供一些意见?

cta-secondary.component.html

<!-- button -->
<button [ngClass]="{'disabled': disabled}" class="btn btn-secondary">
  <span>{{label}}</span>
</button>

cta-secondary.component.ts

import {Component, Input, OnInit, HostListener, ElementRef} from '@angular/core';

@Component({
  selector: 'fuse-cta-secondary',
  templateUrl: './cta-secondary.component.html',
  styleUrls: ['./cta-secondary.component.scss']
})
export class CtaSecondaryComponent implements OnInit {
  // label for cta secondary
  @Input() label: string;
  @Input() disabled: boolean;

  constructor() { }

  ngOnInit() {

  }

}

版本:

角度/核心:8.2.2

业力:6.3.4

茉莉花核:2.99.1

节点:12.18.3

【问题讨论】:

  • 更新:从 chrome-headless 作为浏览器切换到 PhantomJS 似乎已经解决了这个问题。也许 chrome-headless 缓存了一些东西。无论哪种方式,这似乎现在都按预期工作。
  • 我打算告诉你尝试删除 schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],因为我认为你不需要它来查看它是否能解决问题。
  • 是的,我之前尝试解决这个问题时把它留在了那里。正如你所指出的——这对我来说没有任何区别。

标签: javascript angular unit-testing jasmine karma-jasmine


【解决方案1】:

我最终自己“解决”了这个问题。从 chrome-headless 作为 karma.config.js 中的浏览器切换到 PhantomJS 似乎已经解决了这个问题。也许 chrome-headless 缓存了一些东西。无论哪种方式,这似乎现在都按预期工作。

如果需要在 headless-chrome 中完成某种缓存重置,也许其他人可以插话?

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2019-02-12
    • 2021-09-20
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多