gpt4 book ai didi

angular - 使用 primeng 进行单元测试

转载 作者:太空狗 更新时间:2023-10-29 18:18:31 25 4
gpt4 key购买 nike

我尝试在我使用了一些 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>

不确定我需要做什么?我需要注入(inject)或模拟任何东西吗?

这是我的单元测试(基本上是生成的):

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 以忽略子组件。如果您想在测试中使用 slider ,最好模拟它。名为 ngMocks 的库是模拟它的最常见方式,它能够对其输入断言或在输出上发出以断言副作用。

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();
});
});

关于angular - 使用 primeng 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51288255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com