首页 > 解决方案 > 使用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();
  });
});

谢谢

标签: angularunit-testingprimeng

解决方案


当然,您添加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();
    });
});


推荐阅读