【发布时间】:2017-01-31 03:58:16
【问题描述】:
我正在尝试在我的 Angular 2/AngularCLI 应用程序中设置一些单元测试。虽然应用程序按预期工作,但测试显示失败。
所以,简单地开始(或者我是这么想的),我设置了一个从命令行生成的测试组件(ng g c testr)。这将创建一个基本组件测试以及组件文件。当我 CD 进入这个组件,然后使用“ng test”运行这个内置测试时,我得到了与我的应用程序中的其他组件相关的错误。这让我感到困惑,因为我认为单个组件测试是单元测试 - 因此,仅设计用于测试该特定组件。这是组件的示例测试:
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { TestrComponent } from './testr.component';
describe('TestrComponent', () => {
let component: TestrComponent;
let fixture: ComponentFixture<TestrComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ TestrComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestrComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
我认为这应该是“开箱即用”的——因为它是由 AngularCLI 自动设置的。那么为什么会失败呢?我在这里错过了什么吗?这里的测试代码不是用来测试内部组件,而不是它与应用中其他组件的关系吗?
这是我遇到的错误之一的示例。显然,它完全是针对不同的组件。仅仅通过运行这个测试,我就遇到了很多这样的错误。
ERROR in ./src/app/app.component.ts
Module not found: Error: Can't resolve 'app/app.component.html' in '/Users/mko/Documents/abc-cli/abc-cli/cli-abc/src/app'
@ ./src/app/app.component.ts 77:22-55
@ ./src/app/app.component.spec.ts
@ ./src \.spec\.ts
@ ./src/test.ts
这是另一个与不同组件相关的错误:
ERROR in ./src/app/views/client/client-panel.component.ts
Module not found: Error: Can't resolve 'app/views/client/client-panel.component.html' in '/Users/mko/Documents/abc-cli/abc-cli/cli-abc/src/app/views/client'
@ ./src/app/views/client/client-panel.component.ts 34:22-88
@ ./src/app/views/client/client-panel.component.spec.ts
@ ./src \.spec\.ts
@ ./src/test.ts
如果我 cd 进入一个组件并运行“ng test”,是否只运行该组件的单元测试?而且,如果没有,我需要进行哪些更改才能使其仅运行单个组件测试,而不是全部?
【问题讨论】:
-
是的,刚刚添加到上面。除了这个之外,我还收到其他组件的错误消息。不知道为什么。
-
对不起,请澄清。如果我 cd 进入一个组件并运行“ng test”,是否只运行该组件的单元测试?而且,如果没有,我需要进行哪些更改才能使其仅运行单个组件测试,而不是全部?
标签: javascript angular karma-jasmine