NO_ERRORS_SCHEMA 停止 Karma 测试在 Angular 中的工作

Kam*_*aja 2 karma-runner karma-jasmine angular

我有有效的 Angular 测试设置。当我测试内部有嵌套组件的组件时,这会给我带来错误,这就是为什么我需要模拟这些组件。

Angular Test 文档向我们展示了模拟组件的其他方法 - 使用 NO_ERRORS_SCHEMA。当我尝试使用它时(无论是在无头模式还是使用 Chrome 的正常模式下),我的测试都会停止工作。信息看起来像这样

24 03 2019 18:48:45.750:INFO [launcher]: Starting browser Chrome
24 03 2019 18:48:49.599:WARN [karma]: No captured browser, open 
http://localhost:9876/    
24 03 2019 18:48:49.644:INFO [HeadlessChrome 73.0.3683 (Ubuntu 
0.0.0)]: Connected on socket cQvumAWhGFfzQWh0AAAA with id 98993378
Run Code Online (Sandbox Code Playgroud)

在浏览器模式下,我只能看到信息:

Karma v4.0.1 - connected
Chromium 73.0.3683 (Ubuntu 0.0.0) is idle 
Run Code Online (Sandbox Code Playgroud)

当我在没有 [NO_ERRORS_SCHEMA] 的情况下运行测试时,我可以看到我的测试结果,这就是为什么错误与此架构设置相关。

我的组件规格设置:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ContactComponent } from './contact.component';
import { NO_ERRORS_SCHEMA } from '@angular/compiler/src/core';

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

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

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

  it('should create', () => {
    expect(component).toBeFalsy();
  });
});
Run Code Online (Sandbox Code Playgroud)

问题是 - make 测试如何与 NO_ERRORS_SCHEMA 一起使用

我的机器 - Ubuntu 18.04,节点 11.11

"jasmine-core": "~3.3.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^4.0.1",
"karma-chrome-launcher": "~2.2.0",
"karma-cli": "~2.0.0",
"karma-coverage-istanbul-reporter": "^2.0.5",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
Run Code Online (Sandbox Code Playgroud)

Kam*_*aja 7

我似乎没有找到答案。在 devtools 控制台内的 Chrome 测试浏览器窗口中,我发现了一个提示 -

Uncaught Error: Cannot find module 'tslib'
at webpackEmptyContext
Run Code Online (Sandbox Code Playgroud)

谷歌搜索这个,给了我答案 - NO_ERRORS_SCHEMA 的导入声明不正确。

import { NO_ERRORS_SCHEMA } from '@angular/compiler/src/core';
Run Code Online (Sandbox Code Playgroud)

我将其更改为以下后达到了预期的结果:

import { NO_ERRORS_SCHEMA } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)