angular - 使用primeng进行单元测试
问题描述
我尝试在使用了一些primeng组件的组件上编写我的第一个单元测试。
当我运行“ng test”时,我得到了这个错误:
Chrome 63.0.3239 (Linux 0.0.0) HeaderComponent should create FAILED
1. If 'p-dropdown' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'p-dropdown' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("header-text">
<p-dropdown [options]="languages" (onChange)="onDropdownChange($event.value)" [ERROR ->][(ngModel)]="selectedLanguage"></p-dropdown>
</div>
不确定我需要做什么?我需要注入或模拟任何东西吗?
这是我的单元测试(基本上是生成的):
describe('HeaderComponent', () => {
let component: HeaderComponent;
let fixture: ComponentFixture<HeaderComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [],
declarations: [HeaderComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
谢谢
解决方案
当然,您添加NO_ERROR_SCHEMA
忽略子组件。如果您想在测试中使用滑块,最好模拟它。名为ngMocks的 Lib是模拟它的最常用方法,它能够在其输入上断言或在输出上发出以断言副作用。
ngMocks可以通过 npm 添加:npm i ng-mocks
例如,模拟p-slider
组件如下所示:
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {MockComponent} from 'ng-mocks'; //step 1: add mock util function
import {Slider, SliderModule} from 'primeng/slider'; // setp 2: Mocked component and it's module
import {DateRangePickerComponent} from './date-range-picker.component';
describe('DateRangePickerComponent', () => {
let component: DateRangePickerComponent;
let fixture: ComponentFixture<DateRangePickerComponent>;
beforeEach(
async(() => {
TestBed.configureTestingModule({
imports: [SliderModule], // add mocked comp's module
declarations: [
DateRangePickerComponent,
MockComponent(Slider) //actual mocking
]
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(DateRangePickerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
推荐阅读
- c# - 如何在 mongo 中使用 C# .net 运行自定义查询?
- react-native - 如何通过堆栈导航将数据传递到反应原生选项卡上的特定屏幕?
- reactjs - NextJs CORS 问题
- git - Git文件夹和github存储库连接问题
- tensorflow - 使用 GradientTape TensorFlow 计算二阶导数
- typescript - 为什么“任何”类型扩展另一种类型将始终是打字稿中的联合类型?
- c# - 继承类型与Generics类型之间的类型转换
- excel - 如何在数组中复制存储的“特定单元格”?每个(循环)范围的替代方案
- mysql - 如何获取包含最大值且不重复且具有分组依据的数据?
- php - Laravel 8我们如何获得经过身份验证的用户电子邮件地址