Skip to content

Commit

Permalink
feat(tests): add more Single & MultipleSelectEditor unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ghiscoding-SE committed Sep 30, 2019
1 parent c65c781 commit 9dc1abe
Show file tree
Hide file tree
Showing 6 changed files with 574 additions and 138 deletions.
25 changes: 17 additions & 8 deletions src/app/examples/grid-editor.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,33 +180,36 @@ export class GridEditorComponent implements OnInit {
}, {
id: 'duration',
name: 'Duration (days)',
field: 'duration',
field: 'task.duration',
minWidth: 100,
filterable: true,
sortable: true,
formatter: Formatters.complexObject,
type: FieldType.number,
exportWithFormatter: true,
filter: { model: Filters.slider, params: { hideSliderNumber: false } },
/*
editor: {
model: Editors.slider,
minValue: 0,
maxValue: 100,
// params: { hideSliderNumber: true },
},
/*
*/
editor: {
// default is 0 decimals, if no decimals is passed it will accept 0 or more decimals
// however if you pass the "decimalPlaces", it will validate with that maximum
alwaysSaveOnEnterKey: true, // defaults to False, when set to true and user presses ENTER it will always call a Save even if value is empty
model: Editors.float,
placeholder: 'enter number',
title: 'Your number must be bigger than 5', title: 'show a custom title', // add a custom title, to see it as a real tooltip you'll need to implement something like tipsy jquery lib
title: 'Your number must be bigger than 5', // add a custom title, to see it as a real tooltip you'll need to implement something like tipsy jquery lib
minValue: 5,
maxValue: 365,
// the default validation error message is in English but you can override it by using "errorMessage"
// errorMessage: this.i18n.tr('INVALID_FLOAT', { maxDecimal: 2 }),
params: { decimalPlaces: 2 },
},
*/

}, {
id: 'complete',
name: '% Complete',
Expand Down Expand Up @@ -247,11 +250,14 @@ export class GridEditorComponent implements OnInit {
}, {
id: 'start',
name: 'Start',
field: 'start',
field: 'task.start',
minWidth: 100,
filterable: true,
filter: { model: Filters.compoundDate },
formatter: Formatters.dateIso,
formatter: Formatters.multiple,
params: {
formatters: [Formatters.complexObject, Formatters.dateIso,]
},
exportWithFormatter: true,
sortable: true,
type: FieldType.date,
Expand Down Expand Up @@ -383,6 +389,7 @@ export class GridEditorComponent implements OnInit {
sortable: true,
type: FieldType.string,
editor: {
placeholder: 'choose option',
collectionAsync: this.http.get<{ value: string; label: string; }[]>(URL_SAMPLE_COLLECTION_DATA),
// OR a regular collection load
// collection: Array.from(Array(100).keys()).map(k => ({ value: k, prefix: 'Task', label: k })),
Expand Down Expand Up @@ -530,10 +537,12 @@ export class GridEditorComponent implements OnInit {
tempDataset.push({
id: i,
title: 'Task ' + i,
duration: (i % 33 === 0) ? null : Math.round(Math.random() * 100) + '',
task: {
duration: (i % 33 === 0) ? null : Math.round(Math.random() * 100) + '',
start: new Date(randomYear, randomMonth, randomDay),
},
percentComplete: randomPercent,
percentCompleteNumber: randomPercent,
start: new Date(randomYear, randomMonth, randomDay),
finish: randomFinish < new Date() ? '' : randomFinish, // make sure the random date is earlier than today
effortDriven: (i % 5 === 0),
prerequisites: (i % 2 === 0) && i !== 0 && i < 12 ? [i, i - 1] : [],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// import 3rd party lib multiple-select for the tests
import '../../../../../assets/lib/multiple-select/multiple-select';

import { TestBed } from '@angular/core/testing';
import { TranslateService, TranslateModule } from '@ngx-translate/core';
import { Editors } from '../index';
import { MultipleSelectEditor } from '../multipleSelectEditor';
import { CollectionService } from '../../services/collection.service';
import { AutocompleteOption, Column, EditorArgs, EditorArguments, GridOption, KeyCode } from '../../models';

const KEY_CHAR_A = 97;
const containerId = 'demo-container';

// define a <div> container to simulate the grid container
const template = `<div id="${containerId}"></div>`;

const dataViewStub = {
refresh: jest.fn(),
};

const gridOptionMock = {
autoCommitEdit: false,
editable: true,
i18n: null,
} as GridOption;

const getEditorLockMock = {
commitCurrentEdit: jest.fn(),
};

const gridStub = {
getOptions: () => gridOptionMock,
getColumns: jest.fn(),
getEditorLock: () => getEditorLockMock,
getHeaderRowColumn: jest.fn(),
navigateNext: jest.fn(),
navigatePrev: jest.fn(),
render: jest.fn(),
};

describe('SelectEditor', () => {
let divContainer: HTMLDivElement;
let editor: MultipleSelectEditor;
let editorArguments: EditorArguments;
let mockColumn: Column;
let mockItemData: any;
let translate: TranslateService;

beforeEach(() => {
divContainer = document.createElement('div');
divContainer.innerHTML = template;
document.body.appendChild(divContainer);

TestBed.configureTestingModule({
providers: [],
imports: [TranslateModule.forRoot()]
});
translate = TestBed.get(TranslateService);

translate.setTranslation('en', {
CANCEL: 'Cancel',
SAVE: 'Save',
});
translate.setTranslation('fr', {
CANCEL: 'Annuler',
SAVE: 'Sauvegarder',
});
translate.setDefaultLang('fr');

mockColumn = { id: 'gender', field: 'gender', editable: true, editor: { model: Editors.multipleSelect }, internalColumnEditor: {} } as Column;

editorArguments = {
grid: gridStub,
column: mockColumn,
item: mockItemData,
event: null,
cancelChanges: jest.fn(),
commitChanges: jest.fn(),
container: divContainer,
columnMetaData: null,
dataView: dataViewStub,
gridPosition: { top: 0, left: 0, bottom: 10, right: 10, height: 100, width: 100, visible: true },
position: { top: 0, left: 0, bottom: 10, right: 10, height: 100, width: 100, visible: true },
};
});

describe('with valid Editor instance', () => {
beforeEach(() => {
mockItemData = { id: 1, gender: 'male', isActive: true };
mockColumn = { id: 'gender', field: 'gender', editable: true, editor: { model: Editors.multipleSelect }, internalColumnEditor: {} } as Column;
mockColumn.internalColumnEditor.collection = [{ value: 'male', label: 'male' }, { value: 'female', label: 'female' }];

editorArguments.column = mockColumn;
editorArguments.item = mockItemData;
});

afterEach(() => {
editor.destroy();
});

it('should initialize the editor', (done) => {
mockColumn.internalColumnEditor.collection = [{ value: 'male', label: 'male' }, { value: 'female', label: 'female' }];
gridOptionMock.i18n = translate;
editor = new MultipleSelectEditor(editorArguments);
const editorCount = document.body.querySelectorAll('select.ms-filter.editor-gender').length;
const spy = jest.spyOn(editor, 'show');

setTimeout(() => {
expect(spy).toHaveBeenCalled();
expect(editorCount).toBe(1);
done();
});
});

it('should call "setValue" with a single string and expect the string to be returned as an array when calling "getValue"', () => {
editor = new MultipleSelectEditor(editorArguments);
editor.setValue(['male']);

expect(editor.getValue()).toEqual(['male']);
});

it('should hide the DOM element div wrapper when the "hide" method is called', () => {
editor = new MultipleSelectEditor(editorArguments);
const editorElm = document.body.querySelector<HTMLDivElement>('[name=editor-gender].ms-drop');

editor.show();
expect(editorElm.style.display).toBe('');

editor.hide();
expect(editorElm.style.display).toBe('none');
});

it('should show the DOM element div wrapper when the "show" method is called', () => {
editor = new MultipleSelectEditor(editorArguments);
const editorElm = document.body.querySelector<HTMLDivElement>('[name=editor-gender].ms-drop');

editor.hide();
expect(editorElm.style.display).toBe('none');

editor.show();
expect(editorElm.style.display).toBe('');
});
});
});
Loading

0 comments on commit 9dc1abe

Please sign in to comment.