Ошибки Jasmine Unit Testing с использованием пакета ng-select - PullRequest
0 голосов
/ 28 мая 2018

Я импортировал компонент ng-select (https://github.com/ng-select/ng-select) в мое угловое приложение и не выдает никаких консольных ошибок при запуске приложения и работает должным образом. Однако это вызывает ошибки при запуске моих угловых модульных тестов с использованием Jasmine.

Я импортировал NgSelectModule в мой файл app.module.ts в массиве import, и я также импортировал NgSelectComponent в мой файл configuration.component.spec.ts через массив объявлений:

import { NgSelectComponent } from '@ng-select/ng-select';

 describe('Test Configuration Component',
  () => {
    let component: ConfigurationComponent;
    let fixture: ComponentFixture<ConfigurationComponent>;

    beforeEach(() => {
      TestBed.configureTestingModule({
        declarations: [ConfigurationComponent, NgSelectComponent],
        imports: [FormsModule],
        providers: [{ provide: APIService, useClass: APIServiceMock }, Helper]
      });

      fixture = TestBed.createComponent(ConfigurationComponent);
      component = fixture.componentInstance;
    });

Мой модульный тест выглядит следующим образом:

  it('check that array of employees got binded to accounts', async () => {
    fixture.detectChanges();
    let employeeAccounts = [
      { "employeeAccountId": 1, "employeeId": 1, "name": "Name", "descriptor": "descriptor", "street": "Street", "postcode": "postcode", "state": "VIC", "city": "Melb", "country": "AU", "phone": "3123", "MCC": "MCC" },
      { "employeeAccountId": 2, "employeeId": 1, "name": "Name2", "descriptor": "descriptor2", "street": "Street2", "postcode": "postcode2", "state": "VIC2", "city": "Melb2", "country": "AU2", "phone": "3123", "MCC": "MCC2" }];
      component.employeeAccounts = employeeAccounts;
      component.ngOnInit();
      fixture.whenStable().then(() => {
        fixture.detectChanges();
        expect(component.employeeAccounts[1]).toEqual(employeeAccounts[1]);
      });
    });

HTML-код для ng-select в компоненте конфигурации выглядит следующим образом:

<ng-select [(ngModel)]="selectedEmployeeAccountId" [items]="employeeAccounts" (change)="accountSelected()" [disabled]="isLoadingAccounts" [loading]="isLoadingAccounts" bindLabel="name" bindValue="employeeAccountId" placeholder="Please Select"></ng-select>

Мне пришлосьиспользуйте более старую версию ng-select (v 1.5.2) из-за проблем с совместимостью Angular 5.

Ошибка модульного теста:

HeadlessChrome 0.0.0 (Windows 10 0.0.0) Test Configuration Component check that array of employees got binded to accounts FAILED
        Error: Template parse errors:
        Can't bind to 'virtualScroll' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'virtualScroll' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
        <ng-dropdown-panel *ngIf="isOpen"
            class="ng-dropdown-panel"
            [ERROR ->][virtualScroll]="virtualScroll"
            [bufferAmount]="bufferAmount"
            [appendTo]="appendTo"
        "): ng:///DynamicTestModule/NgSelectComponent.html@47:4
        Can't bind to 'bufferAmount' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'bufferAmount' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
            class="ng-dropdown-panel"
            [virtualScroll]="virtualScroll"
            [ERROR ->][bufferAmount]="bufferAmount"
            [appendTo]="appendTo"
            [position]="dropdownPosition"
        "): ng:///DynamicTestModule/NgSelectComponent.html@48:4
        Can't bind to 'appendTo' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'appendTo' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
            [virtualScroll]="virtualScroll"
            [bufferAmount]="bufferAmount"
            [ERROR ->][appendTo]="appendTo"
            [position]="dropdownPosition"
            [headerTemplate]="headerTemplate"
        "): ng:///DynamicTestModule/NgSelectComponent.html@49:4
        Can't bind to 'position' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'position' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
            [bufferAmount]="bufferAmount"
            [appendTo]="appendTo"
            [ERROR ->][position]="dropdownPosition"
            [headerTemplate]="headerTemplate"
            [footerTemplate]="footerTempl"): ng:///DynamicTestModule/NgSelectComponent.html@50:4
        Can't bind to 'headerTemplate' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'headerTemplate' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
            [appendTo]="appendTo"
            [position]="dropdownPosition"
            [ERROR ->][headerTemplate]="headerTemplate"
            [footerTemplate]="footerTemplate"
            [items]="itemsList.filter"): ng:///DynamicTestModule/NgSelectComponent.html@51:4
        Can't bind to 'footerTemplate' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'footerTemplate' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
            [position]="dropdownPosition"
            [headerTemplate]="headerTemplate"
            [ERROR ->][footerTemplate]="footerTemplate"
            [items]="itemsList.filteredItems"
            (update)="viewPortItems ="): ng:///DynamicTestModule/NgSelectComponent.html@52:4
        Can't bind to 'items' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'items' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
            [headerTemplate]="headerTemplate"
            [footerTemplate]="footerTemplate"
            [ERROR ->][items]="itemsList.filteredItems"
            (update)="viewPortItems = $event"
            (scrollToEnd)="scrollToEn"): ng:///DynamicTestModule/NgSelectComponent.html@53:4
        'ng-dropdown-panel' is not a known element:
        1. If 'ng-dropdown-panel' is an Angular component, then verify that it is part of this module.
        2. If 'ng-dropdown-panel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
            </span>
        </div>
        [ERROR ->]<ng-dropdown-panel *ngIf="isOpen"
            class="ng-dropdown-panel"
            [virtualScroll]="virtualScroll"
        "): ng:///DynamicTestModule/NgSelectComponent.html@45:0
            at syntaxError node_modules/@angular/compiler/esm5/compiler.js:486:22)
            at TemplateParser.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.TemplateParser.parse node_modules/@angular/compiler/esm5/compiler.js:24674:1)
            at JitCompiler.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.JitCompiler._parseTemplate node_modules/@angular/compiler/esm5/compiler.js:34629:1)
            at JitCompiler.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.JitCompiler._compileTemplate node_modules/@angular/compiler/esm5/compiler.js:34604:1)
            at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/esm5/compiler.js:34505:48
            at Set.forEach (<anonymous>)
            at JitCompiler.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.JitCompiler._compileComponents node_modules/@angular/compiler/esm5/compiler.js:34505:1)
            at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/esm5/compiler.js:34393:1
            at Object.then node_modules/@angular/compiler/esm5/compiler.js:475:33)
            at JitCompiler.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.JitCompiler._compileModuleAndAllComponents node_modules/@angular/compiler/esm5/compiler.js:34391:1)
        Failed: Cannot read property 'detectChanges' of undefined
        TypeError: Cannot read property 'detectChanges' of undefined
            at Object.<anonymous> src/app/configuration/configuration.component.spec.ts:87:17)
            at step (http://localhost:9876/_karma_webpack_/main.bundle.js:89:23)
            at Object.next (http://localhost:9876/_karma_webpack_/main.bundle.js:70:53)
            at http://localhost:9876/_karma_webpack_/main.bundle.js:64:71
            at new ZoneAwarePromise node_modules/zone.js/dist/zone.js:891:1)
            at webpackJsonp../src/app/configuration/configuration.component.spec.ts.__awaiter (http://localhost:9876/_karma_webpack_/main.bundle.js:60:12)
            at UserContext.<anonymous> src/app/configuration/configuration.component.spec.ts:86:66)
            at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
            at ProxyZoneSpec.webpackJsonp../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:288:1)
            at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:387:1)

Я полагаю, это может быть из-за версии ng- выбор, который я использую, не импортирует все необходимые зависимости, но затем я успешно использую раскрывающийся список во внешнем интерфейсе, поэтому я думаю, что это может быть отдельной проблемой.

ЛюбойПомочь в определении проблемы было бы здорово.

Спасибо!

Ответы [ 2 ]

0 голосов
/ 21 декабря 2018

Добавьте NgSelectModule к вашим импортам, это исправило ошибку для меня.

import {
 NgSelectModule
} from '@ng-select/ng-select';

describe('Test Configuration Component',
() => {
 let component: ConfigurationComponent;
 let fixture: ComponentFixture < ConfigurationComponent > ;

 beforeEach(() => {
   TestBed.configureTestingModule({
     declarations: [ConfigurationComponent],
     imports: [FormsModule, NgSelectModule],
     providers: [{
       provide: APIService,
       useClass: APIServiceMock
     }, Helper]
   });

   fixture = TestBed.createComponent(ConfigurationComponent);
   component = fixture.componentInstance;
 });

Редактирование: форматирование.

0 голосов
/ 12 декабря 2018

У меня была такая же ошибка, и я не нашел способа отдельно ввести 'ng-dropdown-panel'.Чтобы обойти это для тестирования, вы можете установить схемы: [NO_ERRORS_SCHEMA] в вашем тестовом стенде, чтобы предотвратить возникновение этой ошибки

Настройте свой тест, как показано ниже:

import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

beforeEach(async(() => {
 TestBed.configureTestingModule({
  imports: [FormsModule, ReactiveFormsModule],
  declarations: [TestComponent, NgSelectComponent],
  providers: [],
  schemas:[NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...