在 Angular CLI 应用程序中使用 Karma 执行单元测试时未找到对象
No object is found when executing unit-tests with Karma in Angular CLI app
我已经使用 Angular CLI 设置了我的项目。我还通过 "ng g component NAME" 创建了我的组件。这也自动添加了一个 test-class 来创建我的单元测试(这当然非常简洁)。
问题是,即使我将它们保留在初始状态,我的测试也很难失败。我想在实际编写任何测试之前对其进行测试。但是,测试非常失败。没有一行执行得很好。
> ng test
'app-some-selector' is not a known element:
1. If 'app-some-selector' is an Angular component, then verify that it is part of this module.
或者例如
The pipe 'myPipe' could not be found
特定组件中的每个对象都会抛出上述错误。如果通过它的选择器使用另一个组件,则找不到相应的组件,如果通过依赖注入使用像 http 这样的服务,编译器会声明没有它的提供者等等。
顺便说一句,我的项目在 ng serve
下运行得很好。
当您通过 angular-cli 创建组件时,它会为您创建
it('should create', () => {
expect(component).toBeTruthy();
});
第一个测试尝试创建一个组件,如果你添加一个依赖项,例如其他组件,它就会失败。
要通过此测试,您需要在 beforeEach
函数中更新在测试 class 中创建组件的方式:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ myComponent ],
providers: [myService]
})
.compileComponents();
}));
在这里,如果我在我的组件测试依赖注入中添加一个服务 myService
。像这样,您可以将模拟对象作为 myService
更轻松地测试您的组件。
我已经使用 Angular CLI 设置了我的项目。我还通过 "ng g component NAME" 创建了我的组件。这也自动添加了一个 test-class 来创建我的单元测试(这当然非常简洁)。
问题是,即使我将它们保留在初始状态,我的测试也很难失败。我想在实际编写任何测试之前对其进行测试。但是,测试非常失败。没有一行执行得很好。
> ng test
'app-some-selector' is not a known element:
1. If 'app-some-selector' is an Angular component, then verify that it is part of this module.
或者例如
The pipe 'myPipe' could not be found
特定组件中的每个对象都会抛出上述错误。如果通过它的选择器使用另一个组件,则找不到相应的组件,如果通过依赖注入使用像 http 这样的服务,编译器会声明没有它的提供者等等。
顺便说一句,我的项目在 ng serve
下运行得很好。
当您通过 angular-cli 创建组件时,它会为您创建
it('should create', () => {
expect(component).toBeTruthy();
});
第一个测试尝试创建一个组件,如果你添加一个依赖项,例如其他组件,它就会失败。
要通过此测试,您需要在 beforeEach
函数中更新在测试 class 中创建组件的方式:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ myComponent ],
providers: [myService]
})
.compileComponents();
}));
在这里,如果我在我的组件测试依赖注入中添加一个服务 myService
。像这样,您可以将模拟对象作为 myService
更轻松地测试您的组件。