Skip to content

Commit

Permalink
chore(primeng) fix unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
nicobytes committed Aug 26, 2024
1 parent 2802d40 commit bd54c75
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 77 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ describe('DotEditPageViewAsControllerSeoComponent', () => {

componentHost.pageState = new DotPageRenderState(mockUser(), mockDotRenderedPage());



fixtureHost.detectChanges();

languageSelector = de.query(By.css('dot-language-selector')).componentInstance;
Expand All @@ -205,11 +207,10 @@ describe('DotEditPageViewAsControllerSeoComponent', () => {
expect(personaSelector).not.toBeNull();
});

xit('should persona selector be enabled', () => {
expect(personaSelector.disabled).toBe(false);
});
fit('should persona selector be disabled after haveContent is set to false', () => {

console.log('componentHost.pageState', componentHost.pageState.page.identifier);

it('should persona selector be disabled after haveContent is set to false', () => {
const dotPageStateService: DotPageStateService = de.injector.get(DotPageStateService);
dotPageStateService.haveContent$.next(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default meta;

type Story = StoryObj<Args>;

export const Primary: Story = {
export const Default: Story = {
parameters: {
docs: {
source: {
Expand All @@ -76,3 +76,19 @@ export const Primary: Story = {
}
}
};

export const CustomTemplate: Story = {
render: (args) => ({
props: args,
template: `
<p-dropdown [options]="options" [style]="{'width': width + 'px'}">
<ng-template let-selected pTemplate="selectedItem">
--{{ selected.label }}--
</ng-template>
<ng-template let-item pTemplate="item">
**{{ item.label }}**
</ng-template>
</p-dropdown>`
})
};

Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createFakeEvent } from '@ngneat/spectator';
import {
createServiceFactory,
mockProvider,
Expand Down Expand Up @@ -255,18 +256,24 @@ describe('DotExperimentsConfigurationStore', () => {

store.vm$.pipe(take(1)).subscribe(({ menuItems }) => {
// Start Experiment
menuItems[MENU_ITEMS_START_INDEX].command();
menuItems[MENU_ITEMS_START_INDEX].command({
originalEvent: createFakeEvent('click')
});
expect(dotExperimentsService.start).toHaveBeenCalledWith(EXPERIMENT_MOCK.id);

// Push Publish
menuItems[MENU_ITEMS_PUSH_PUBLISH_INDEX].command();
menuItems[MENU_ITEMS_PUSH_PUBLISH_INDEX].command({
originalEvent: createFakeEvent('click')
});
expect(dotPushPublishDialogService.open).toHaveBeenCalledWith({
assetIdentifier: EXPERIMENT_MOCK.id,
title: 'Push Publish'
});

// Add to Bundle
menuItems[MENU_ITEMS_ADD_T0_BUNDLE_INDEX].command();
menuItems[MENU_ITEMS_ADD_T0_BUNDLE_INDEX].command({
originalEvent: createFakeEvent('click')
});
expect(store.showAddToBundle).toHaveBeenCalledWith(EXPERIMENT_MOCK.id);

// test the ones with confirm dialog in the DotExperimentsConfigurationComponent.
Expand Down
19 changes: 9 additions & 10 deletions core-web/libs/portlets/edit-ema/portlet/src/test-setup.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import 'jest-preset-angular/setup-jest';

import { SplitButtonMockComponent, SplitButtonMockModule } from '@dotcms/utils-testing';

/*
* This is a workaround for the following PrimeNg issue: https://github.com/primefaces/primeng/issues/12945
* They already fixed it, but it's not in the latest v15 LTS yet: https://github.com/primefaces/primeng/pull/13597
*/
jest.mock('primeng/splitbutton', () => ({
SplitButtonModule: SplitButtonMockModule,
SplitButton: SplitButtonMockComponent
}));
// Workaround for the following issue:
// https://github.com/jsdom/jsdom/issues/2177#issuecomment-1724971596
const originalConsoleError = console.error;
const jsDomCssError = 'Error: Could not parse CSS stylesheet';
console.error = (...params) => {
if (!params.find((p) => p.toString().includes(jsDomCssError))) {
originalConsoleError(...params);
}
};
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import { createFakeEvent } from '@ngneat/spectator';
import { of } from 'rxjs';

import { Component, DebugElement, EventEmitter, Input, Output } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { ButtonModule } from 'primeng/button';
import { Dropdown, DropdownModule } from 'primeng/dropdown';
Expand All @@ -15,7 +17,7 @@ import { TableModule } from 'primeng/table';
import { DotMessageService, DotFormatDateService } from '@dotcms/data-access';
import { DotcmsConfigService, LoginService } from '@dotcms/dotcms-js';
import { DotDiffPipe, DotMessagePipe, DotRelativeDatePipe } from '@dotcms/ui';
import { MockDotMessageService } from '@dotcms/utils-testing';
import { MockDotMessageService, mockMatchMedia } from '@dotcms/utils-testing';

import { DotContentCompareTableComponent } from './dot-content-compare-table.component';

Expand Down Expand Up @@ -296,7 +298,8 @@ describe('DotContentCompareTableComponent', () => {
DotMessagePipe,
FormsModule,
DotRelativeDatePipe,
ButtonModule
ButtonModule,
BrowserAnimationsModule
],
providers: [
{ provide: DotMessageService, useValue: messageServiceMock },
Expand Down Expand Up @@ -324,6 +327,7 @@ describe('DotContentCompareTableComponent', () => {
de = hostFixture.debugElement;
hostComponent.data = dotContentCompareTableDataMock;
hostFixture.detectChanges();
mockMatchMedia();
});

describe('header', () => {
Expand All @@ -347,11 +351,20 @@ describe('DotContentCompareTableComponent', () => {
{ label: 'Plain', value: false }
]);
});
it('should show versions selectButton with transformed label', () => {
const dropdown = de.query(By.css('[data-testId="versions-dropdown"]')).nativeElement;
expect(dropdown.innerHTML.replace(/^\s+|\s+$/gm, '')).toContain(
`${dotContentCompareTableDataMock.versions[0].modDate} by ${dotContentCompareTableDataMock.versions[0].modUserName}`
);
it('should show versions selectButton with transformed label', async () => {
const dropdown = de.query(By.css('p-dropdown'));


dropdown.componentInstance.show();
hostFixture.detectChanges();

const versions = hostComponent.data.versions;

dropdown.queryAll(By.css('.p-dropdown-item')).forEach((item, index) => {
const textContent = item.nativeElement.textContent;
const text = `${versions[index].modDate} by ${versions[index].modUserName}`
expect(textContent).toContain(text);
});
});
});

Expand Down Expand Up @@ -469,7 +482,7 @@ describe('DotContentCompareTableComponent', () => {
it('should emit changeVersion', () => {
jest.spyOn(hostComponent.changeVersion, 'emit');
const dropdown: Dropdown = de.query(By.css('p-dropdown')).componentInstance;
dropdown.onChange.emit({ value: 'test' });
dropdown.onChange.emit({ value: 'test', originalEvent: createFakeEvent('click') });

expect(hostComponent.changeVersion.emit).toHaveBeenCalledWith('test');
});
Expand Down
23 changes: 9 additions & 14 deletions core-web/libs/portlets/edit-ema/ui/src/test-setup.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
globalThis.ngJest = {
testEnvironmentOptions: {
errorOnUnknownElements: true,
errorOnUnknownProperties: true
import 'jest-preset-angular/setup-jest';

// Workaround for the following issue:
// https://github.com/jsdom/jsdom/issues/2177#issuecomment-1724971596
const originalConsoleError = console.error;
const jsDomCssError = 'Error: Could not parse CSS stylesheet';
console.error = (...params) => {
if (!params.find((p) => p.toString().includes(jsDomCssError))) {
originalConsoleError(...params);
}
};
import 'jest-preset-angular/setup-jest';

import { SplitButtonMockComponent, SplitButtonMockModule } from '@dotcms/utils-testing';

/*
* This is a workaround for the following PrimeNg issue: https://github.com/primefaces/primeng/issues/12945
* They already fixed it, but it's not in the latest v15 LTS yet: https://github.com/primefaces/primeng/pull/13597
*/
jest.mock('primeng/splitbutton', () => ({
SplitButtonModule: SplitButtonMockModule,
SplitButton: SplitButtonMockComponent
}));
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
dotSelectItem
data-testId="autocomplete"
inputId="auto-complete-input"
appendTo="body"></p-autoComplete>
appendTo="body" />
<ng-container *ngIf="isJsonClasses$ | async; else suggestionNotes">
<ul data-testId="list">
<li>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, it } from '@jest/globals';
import { createFakeEvent } from '@ngneat/spectator';
import { Spectator, byTestId, createComponentFactory } from '@ngneat/spectator/jest';
import { of, throwError } from 'rxjs';

Expand All @@ -12,7 +13,7 @@ import { DynamicDialogConfig, DynamicDialogRef, DynamicDialogModule } from 'prim

import { DotMessageService } from '@dotcms/data-access';
import { DotMessagePipe } from '@dotcms/ui';
import { MockDotMessageService } from '@dotcms/utils-testing';
import { MockDotMessageService, mockMatchMedia } from '@dotcms/utils-testing';

import { AddStyleClassesDialogComponent } from './add-style-classes-dialog.component';
import { JsonClassesService } from './services/json-classes.service';
Expand Down Expand Up @@ -86,6 +87,7 @@ describe('AddStyleClassesDialogComponent', () => {
service = spectator.inject(JsonClassesService);
dialogRef = spectator.inject(DynamicDialogRef);
autocomplete = spectator.query(AutoComplete);
mockMatchMedia();
});

it('should set attributes to autocomplete', () => {
Expand Down Expand Up @@ -122,23 +124,11 @@ describe('AddStyleClassesDialogComponent', () => {

it('should filter suggestions and pass to autocomplete on completeMethod', () => {
spectator.detectChanges();
spectator.triggerEventHandler(AutoComplete, 'completeMethod', { query: 'class1' });
spectator.triggerEventHandler(AutoComplete, 'completeMethod', { query: 'class1', originalEvent: createFakeEvent('click') });

expect(autocomplete.suggestions).toEqual(['class1']);
});

it('should add class on keyup.enter', () => {
const selectItemSpy = jest.spyOn(autocomplete, 'selectItem');
spectator.detectChanges();

const input = document.createElement('input');
input.value = 'class1';

spectator.triggerEventHandler(AutoComplete, 'onKeyUp', { key: 'Enter', target: input });

expect(selectItemSpy).toBeCalledWith('class1');
});


it('should save selected classes and close the dialog', () => {
spectator.component.selectedClasses = ['class1'];
spectator.component.save();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ describe('TemplateBuilderThemeSelectorComponent', () => {
spectator.component.ngOnInit();

spectator.detectChanges();
spectator.component.dataView.onLazyLoad.emit({ first: 0 });
spectator.component.dataView.onLazyLoad.emit({ first: 0, rows:0, sortField: '', sortOrder: 0 });

expect(paginatorService.getWithOffset).toHaveBeenCalledWith(0);
});
Expand Down
19 changes: 9 additions & 10 deletions core-web/libs/template-builder/src/test-setup.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import 'jest-preset-angular/setup-jest';

import { SplitButtonMockComponent, SplitButtonMockModule } from '@dotcms/utils-testing';

/*
* This is a workaround for the following PrimeNg issue: https://github.com/primefaces/primeng/issues/12945
* They already fixed it, but it's not in the latest v15 LTS yet: https://github.com/primefaces/primeng/pull/13597
*/
jest.mock('primeng/splitbutton', () => ({
SplitButtonModule: SplitButtonMockModule,
SplitButton: SplitButtonMockComponent
}));
// Workaround for the following issue:
// https://github.com/jsdom/jsdom/issues/2177#issuecomment-1724971596
const originalConsoleError = console.error;
const jsDomCssError = 'Error: Could not parse CSS stylesheet';
console.error = (...params) => {
if (!params.find((p) => p.toString().includes(jsDomCssError))) {
originalConsoleError(...params);
}
};
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
@for (action of groupedActions(); track $index; let first = $first) {
@for (action of groupedActions(); track $index;) {
@if (action.length > 1) {
<p-splitButton
(onClick)="action[0].command()"
(onClick)="action[0].command({originalEvent: $event})"
[disabled]="loading"
[styleClass]="sizeClass"
[model]="action | slice: 1"
[outlined]="!first"
[outlined]="!$first"
[label]="action[0].label" />
} @else {
<p-button
(onClick)="action[0].command()"
(onClick)="action[0].command({originalEvent: $event})"
[loading]="loading"
[styleClass]="sizeClass + (!first ? ' p-button-outlined' : '')"
[styleClass]="sizeClass + (!$first ? ' p-button-outlined' : '')"
[label]="action[0].label" />
}
} @empty {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ describe('DotWorkflowActionsComponent', () => {
it('should have default size', () => {
const { button, splitButton } = getComponents(spectator);
expect(button.styleClass.trim()).toBe('');
expect(splitButton.styleClass.trim()).toBe('p-button-outlined');
expect(splitButton.styleClass.trim()).toBe('');
});

it('should set style class p-button-sm', () => {
Expand All @@ -211,7 +211,7 @@ describe('DotWorkflowActionsComponent', () => {

const { button, splitButton } = getComponents(spectator);

expect(splitButton.styleClass.trim()).toBe('p-button-sm p-button-outlined');
expect(splitButton.styleClass.trim()).toBe('p-button-sm');
expect(button.styleClass.trim()).toBe('p-button-sm');
});

Expand All @@ -222,7 +222,7 @@ describe('DotWorkflowActionsComponent', () => {
const { button, splitButton } = getComponents(spectator);

expect(button.styleClass.trim()).toBe('p-button-lg');
expect(splitButton.styleClass.trim()).toBe('p-button-lg p-button-outlined');
expect(splitButton.styleClass.trim()).toBe('p-button-lg');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ import {
signal
} from '@angular/core';

import { MenuItem } from 'primeng/api';
import { ButtonModule } from 'primeng/button';
import { SplitButtonModule } from 'primeng/splitbutton';

import { CustomMenuItem, DotCMSActionSubtype, DotCMSWorkflowAction } from '@dotcms/dotcms-models';

import { DotMessagePipe } from '../../dot-message/dot-message.pipe';


type ButtonSize = 'normal' | 'small' | 'large';

const InplaceButtonSizePrimeNg: Record<ButtonSize, string> = {
Expand All @@ -39,7 +41,7 @@ export class DotWorkflowActionsComponent implements OnChanges {
@Input() size: ButtonSize = 'normal';
@Output() actionFired = new EventEmitter<DotCMSWorkflowAction>();

protected groupedActions = signal<CustomMenuItem[][]>([]);
protected groupedActions = signal<MenuItem[][]>([]);
protected sizeClass: string;

ngOnChanges(): void {
Expand All @@ -57,7 +59,7 @@ export class DotWorkflowActionsComponent implements OnChanges {
* @return {*} {MenuItem[][]}
* @memberof DotWorkflowActionsComponent
*/
private groupActions(actions: DotCMSWorkflowAction[] = []): CustomMenuItem[][] {
private groupActions(actions: DotCMSWorkflowAction[] = []): MenuItem[][] {
return actions
?.reduce(
(acc, action) => {
Expand Down

0 comments on commit bd54c75

Please sign in to comment.