我是第一次尝试 Angular 5 单元测试。虽然我已经创建了应用程序然后决定在其中运行测试。但是我收到了这些错误:
AppComponent should create the app
AppComponent should have as title 'app'
AppComponent should render title in a h1 tag
GalleryComponent should create
UploadComponent should create
和错误详细信息,例如:
Failed: Template parse errors:
'app-upload' is not a known element:
1. If 'app-upload' is an Angular component, then verify that it is part of this module.
2. If 'app-upload' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (" class="row">
<div class="col-md-3" style="padding:5%; box-sizing: border-box">
[ERROR ->]<app-upload></app-upload>
</div>
<div class="col-md-9">
"): ng:///DynamicTestModule/AppComponent.html@3:12
我的 package.json 开发依赖:
devDependencies": {
"@angular/compiler-cli": "^6.0.2",
"@angular-devkit/build-angular": "~0.6.3",
"typescript": "~2.7.2",
"@angular/cli": "~6.0.3",
"@angular/language-service": "^6.0.2",
"@types/jasmine": "2.8.6",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~1.4.2",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1"
}
测试文件app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to Typito-photo-app!');
}));
});
我不知道如何解决这些问题。我没有对规范文件进行任何更改,也没有编写任何测试用例。根据 Angular 文档中的描述,所有这些不应该按预期运行吗?
最佳答案
您要测试的组件有一个或多个子组件
。一个好的做法是忽略这些组件并单独测试它们。
实现此目的的一种方法是使用 NO_ERRORS_SCHEMA 告诉您的 Angular Testbed
在组件构建期间跳过这些在您的 Testbed
中。
从'@angular/core'导入{NO_ERRORS_SCHEMA};
然后你的测试床应该是这样的:
TestBed.configureTestingModule({
declarations: [
AppComponent
],
schemas: [
NO_ERRORS_SCHEMA
]
}).compileComponents();
它应该忽略出现在您的 component.html
中的所有自定义元素(标签)。
另一种方法是模拟您的子组件。例如 this
关于 "components should create "测试用例的 Angular 5 单元测试抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53618822/