Our powerful JS Calendar component


Post by juris »

Hello together,

if we try to execute our unit test with jest we get following error message:

Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

C:\Users\exfho03\IdeaProjects\calendar-frontend\node_modules\@bryntum\calendar\calendar.module.js:206380
export { AbstractAssignmentStoreMixin, AbstractCalendarManagerStoreMixin, AbstractCalendarMixin, AbstractCrudManager, AbstractCrudManagerMixin, AbstractCrudManagerValidation, AbstractDependencyStoreMixin, AbstractEventStoreMixin, AbstractHasAssignmentsMixin, AbstractPartOfProjectGenericMixin, AbstractPartOfProjectModelMixin, AbstractPartOfProjectStoreMixin, AbstractRecurrenceIterator, AbstractResourceStoreMixin, AbstractTimeRanges, ActionBase, ActionColumn, AgendaColumn, AgendaView, AggregateColumn, AjaxHelper, AjaxStore, AjaxTransport, Animator, ArrayDataField, ArrayHelper, AssignmentModel, AssignmentModelMixin, AssignmentStore, AssignmentStoreMixin, AsyncHelper, AttachToProjectMixin, AvatarRendering, Badge, Bag, Bar, Base$1 as Base, BooleanCombo, BooleanDataField, BrowserHelper, Button, ButtonGroup, CI, CIFromSetOrArrayOrValue, CSSHelper, Calendar, CalendarCache, CalendarCacheInterval, CalendarCacheIntervalMultiple, CalendarCacheMultiple, CalendarCacheSingle, CalendarDrag, CalendarFeature, CalendarIntervalMixin, CalendarIntervalStore, CalendarIteratorResult, CalendarMixin, CalendarPanel, CalendarRow, CalendarStores, CellEdit, CellMenu, CellTooltip, CheckColumn, Checkbox, ChipView, Base as ChronoMixinBase, ClickRepeater, ClockTemplate, CollapseTool, Collection, CollectionFilter, CollectionSorter, Column, ColumnAutoWidth, ColumnDragToolbar, ColumnLines, ColumnPicker, ColumnReorder, ColumnResize, ColumnStore, Combo, Config, ConstraintIntervalSide, ConstraintType, Container, ContextMenuBase, CoreAssignmentMixin, CoreAssignmentStoreMixin, CoreCalendarManagerStoreMixin, CoreCalendarMixin, CoreDependencyMixin, CoreDependencyStoreMixin, CoreEventMixin, CoreEventStoreMixin, CoreHasAssignmentsMixin, CoreHasDependenciesMixin, CorePartOfProjectGenericMixin, CorePartOfProjectModelMixin, CorePartOfProjectStoreMixin, CoreResourceMixin, CoreResourceStoreMixin, CrudManager, CrudManagerView, DailyRecurrenceIterator, DataField, DataGenerator, DateColumn, DateDataField, DateField, DateHelper, DatePicker, DateRangeOwner, DateTimeField, DayCellCollecter, DayCellRenderer, DayLayout, DaySelectable, DaySelector, DayTime, DayView, Delayable, DelayableWrapper, DemoBot, Dependencies, DependenciesCalendar, DependencyBaseModel, DependencyCreation, DependencyEdit, DependencyModel, DependencyStore, DependencyStoreMixin, DependencyTooltip, DependencyType, DependencyValidationResult, Direction, DisplayField, DomClassList, DomDataStore, DomHelper, DomSync, DragBase, DragContext, DragCreateBase, DragHelper, DragProxy, DragTipProxy, Draggable, Droppable, Duration, DurationColumn, DurationField, DynamicObject, EdgeInclusion, EditBase, Editor, EventColumn, EventCopyPaste, EventDayIndex, EventDrag, EventDragCreate, EventDragSelect, EventEdit, EventFilter, EventHelper, EventList, EventMenu, EventModel, EventModelMixin, EventNavigation, EventResize, EventSelection, EventSlots, EventSorter, EventStore, EventStoreMixin, EventTip, EventTooltip, Events, ExcelExporter, ExportDialog, ExportOrientationCombo, ExportRowsCombo, Exporter, ExternalEventSource, Factoryable, Featureable, Fencible, Field, FieldContainer, FieldSet, FileField, FileFormat, FilePicker, Filter, FilterBar, FilterField, Finalizable, FluidDayLayout, Footer, Formatter, Fullscreen, FunctionHelper, GetEventsMixin, GlobalEvents, Grid, GridBase, GridElementEvents, ExcelExporter$1 as GridExcelExporter, GridFeatureManager, GridFeatures, GroupSummary$1 as GridGroupSummary, MultiPageExporter$1 as GridMultiPageExporter, MultiPageVerticalExporter$1 as GridMultiPageVerticalExporter, PdfExport$1 as GridPdfExport, GridResponsive, GridRowModel, GridSelection, SinglePageExporter$1 as GridSinglePageExporter, GridState, GridSubGrids, Summary$1 as GridSummary, Group, GroupSummary, Header$1 as Header, HeaderMenu, HeaderZoom, Histogram, HorizontalLayoutPack, HorizontalLayoutStack, HorizontalRendering, HorizontalTimeAxis, Hoverable, IdHelper, Identifiable, IndexPosition, InstancePlugin, IntegerDataField, IntervalCache, JsonEncoder, KeyMap, Label, Labelable, Labels, Layout, List, LoadMaskable, LoadOnDemand, LocaleHelper, LocaleManagerSingleton as LocaleManager, Localizable, LocalizableCombo, LocalizableComboItems, Location, MAX_DATE, MI, MIN_DATE, Mask, Menu, MenuItem, MergeCells, MessageDialog, Model, ModelDataField, ModelStm, Month, MonthView, MonthlyRecurrenceIterator, MultiPageExporter, MultiPageVerticalExporter, Navigator, NonWorkingTime, NumberColumn, NumberDataField, NumberField, NumberFormat, ObjectDataField, ObjectHelper, Objects, Orientation, OverflowPopup, Override, PackMixin, PagingToolbar, Pan, Panel, PanelCollapser, PanelCollapserOverlay, PaperFormat, Parser, PartOfBaseProject, PartOfProject, PasswordField, PdfExport, PercentColumn, PickerField, Pluggable, Point, Popup, pm as PresetManager, PresetStore, Print, ProjectCombo, ProjectConsumer, ProjectCrudManager, ProjectModel, ProjectModelMixin, ProjectType, Promissory, QuickFind, RTL, Radio, RadioGroup, RandomGenerator, RatingColumn, Rectangle, RectangularPathFinder, RecurrenceCombo, RecurrenceConfirmationPopup, RecurrenceDayRuleEncoder, RecurrenceDaysButtonGroup, RecurrenceDaysCombo, RecurrenceEditor, RecurrenceFrequencyCombo, RecurrenceLegend, RecurrenceLegendButton, RecurrenceModel, RecurrenceMonthDaysButtonGroup, RecurrenceMonthsButtonGroup, RecurrencePositionsCombo, RecurrenceStopConditionCombo, RecurringEventEdit, RecurringEvents, RecurringEventsMixin, RecurringTimeSpan, RecurringTimeSpansMixin, RegionResize, Renderable, ResizeHelper, ResizeMonitor, ResourceCollapseColumn, ResourceCombo, ResourceFilter, ResourceHeader, ResourceInfoColumn, ResourceModel, ResourceModelMixin, ResourceStore, ResourceStoreMixin, ResourceTimeRangeModel, ResourceTimeRangeStore, ResourceTimeRanges, ResourceTimeRangesBase, ResourceView, Responsive, Ripple, Rotatable, Row, RowCopyPaste, RowExpander, RowManager, RowNumberColumn, RowReorder, RowsRange, Scale, ScheduleContext, ScheduleMenu, ScheduleRange, ScheduleRangeCombo, ScheduleTableExporter, ScheduleTooltip, Scheduler, SchedulerBase, SchedulerCoreEvent, SchedulerCoreProjectMixin, SchedulerDatePicker, SchedulerDom, SchedulerDomEvents, EventEdit$1 as SchedulerEventEdit, EventEditor$1 as SchedulerEventEditor, EventMenu$1 as SchedulerEventMenu, SchedulerEventNavigation, SchedulerEventRendering, SchedulerEventSelection, EventTooltip$1 as SchedulerEventTooltip, SchedulerExportDialog, SchedulerRegions, ScheduleMenu$1 as SchedulerScheduleMenu, SchedulerScroll, SchedulerState, SchedulerStores, SchedulingMode, ScrollManager, Scroller, Search, SharedEventStoreMixin, Sidebar, SimpleEventEdit, SinglePageExporter, SlideToggle, Slider, Sort, SortedMap, Splitter, State, StateBase, StateProvider, StateStorage, StateTrackingManager, StickyCells, StickyEvents, Store, StoreCRUD, StoreChained, StoreChanges, StoreFilter, StoreGroup, StoreProxy, StoreRelation, StoreSearch, StoreSort, StoreState, StoreStm, StoreSum, StoreSync, StoreTree, StringDataField, StringHelper, Stripe, Styleable, SubGrid, Summary, Tab, TabBar, TabPanel, TableExporter, TemplateColumn, TemplateHelper, TextAreaField, TextAreaPickerField, TextField, TimeAxis, TimeAxisColumn, TimeAxisHeaderMenu, TimeAxisSubGrid, TimeAxisViewModel, TimeColumn, TimeField, TimePicker, TimeRanges, TimeSpan, TimeSpanMenuBase, TimeUnit, TimelineBase, TimelineDateMapper, TimelineDomEvents, TimelineEventRendering, TimelineScroll, TimelineState, TimelineSummary, TimelineViewPresets, TimelineZoomable, Toast, Tool, Toolable, Toolbar, Tooltip, TooltipBase, Transaction, Tree, TreeColumn, TreeGrid, TreeGroup, TreeNode, TrialButton, TrialPanel, UndoRedo, UndoRedoBase, UnspecifiedTimeIntervalModel, VersionHelper, VerticalRendering, VerticalTimeAxisColumn, ViewPreset, WalkHelper, WebSocketManager, WeekExpander, WeekView, WeeklyRecurrenceIterator, Widget, WidgetColumn, WidgetHelper, XMLHelper, YearView, YearlyRecurrenceIterator, binarySearch, combineCalendars, delay, format, isDateFinite, isNotNumber, later, stripDuplicates, unitMagnitudes };
^^^^^^

SyntaxError: Unexpected token 'export'

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at node_modules/@bryntum/calendar-angular/bundles/bryntum-calendar-angular.umd.js:2:111
  at Object.<anonymous> (node_modules/@bryntum/calendar-angular/bundles/bryntum-calendar-angular.umd.js:5:2)

Does anyone know why this is happening or have seen this error message before?

If more information is needed I will provided them asap.

Thank you very much an best regards!


Post by mats »

Not sure as we don't use Jest, does this SO post offer any insights? https://stackoverflow.com/questions/49263429/jest-gives-an-error-syntaxerror-unexpected-token-export


Post by alexp »

Hi juris,
we had the same situation after upgrading Scheduler from v5.0.1. to v5.1.2 which contains the breaking changes of the modules, https://www.bryntum.com/docs/scheduler/guide/Scheduler/upgrades/5.1.0#new-module-bundle-for-angular

First we tried to let jest transform the scheduler as well with a modified transformIgnorePatterns:

module.exports = {
  preset: '../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  transform: {
    '^.+.(ts|mjs|js|html)$': 'jest-preset-angular'
  },
  transformIgnorePatterns: ['node_modules/(?!(.*.mjs$)|@bryntum/)'],
  globals: {
    'ts-jest': {
      stringifyContentPathRegex: '\\.(html|svg)$',
      tsconfig: '<rootDir>/tsconfig.spec.json'
    }
  },
  coverageDirectory: '../../coverage/apps/dispatch',
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment'
  ],
  testEnvironment: 'jsdom'
};
 

But we couldn't get jest to transform the async generator functions:

Uncaught (in promise): Error: Transform failed with 4 errors:
    /<project path>/node_modules/@bryntum/scheduler/scheduler.module.js:109849:36: ERROR: Transforming async generator functions to the configured target environment ("es2015") is not supported yet
    ...

And it seems our version of jest-preset-angular only supports es2015 and es2016 (we use ng13+nx13).

So we just mocked the whole library in our unit tests, because we also have Cypress e2e tests to cover the features.
We created a jest module mock according to our implementation and calls to the scheduler package, you want to adjust your mock:

<lib or project root>/__mocks__/@bryntum/scheduler.js
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable unicorn/no-static-only-class */

// This is a minimal module mock in order to not require and transpile the scheduler package in unit tests

class DragHelper {
  construct(config) {
    this.config = config;
  }
  on() {}
  destroy() {}
}
class EventModel {}
class ResourceModel {}
class Tooltip {
  destroy() {}
}
const LocaleManager = {
  registerLocale() {}
};
class Scheduler {
  suspendRefresh() {}
  resumeRefresh() {}
  timeRangeStore = new ResourceTimeRangeStore();
}
class DomHelper {
  static setTranslateX() {}
  static setTranslateY() {}
  static up() {}
  static getParents() {
    return [];
  }
}

const StringHelper = {
  uncapitalize() {}
};
class ResourceStore {}
class ResourceTimeRangeStore {
  data = {};
}
class EventStore {}
class Rectangle {
  static client() {}
}

module.exports = {
  DomHelper,
  DragHelper,
  EventModel,
  EventStore,
  LocaleManager,
  Rectangle,
  ResourceModel,
  ResourceStore,
  ResourceTimeRangeStore,
  Scheduler,
  StringHelper,
  Tooltip
};

Hope that helps, cheers


Post by mats »

@alexp: Thanks so much for helping! :)


Post by juris »

@alexp: Thank you very much!!!

The error messages are now gone for the scheduler pro but we now get the following error message for the calendar:

 Importing BryntumCalendarModule which does not have a ɵmod property

Our mock file looks like this:

/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable unicorn/no-static-only-class */

// This is a minimal module mock in order to not require and transpile the calendar package in unit tests

class BryntumCalendarModule {}
class BryntumCalendarComponent {
  instance = {};
  eventStore = {};
}

module.exports = {
  BryntumCalendarModule,
  BryntumCalendarComponent
};

Any idea what I have forgotten or done wrong?

Thank you in advance and best regards!


Post by alexp »

@juris,

this sounds an Angular module problem. I think somewhat expects your BryntumCalendarModule to be a real module. So find out, what/where and try to mock it using some tools for that (I like ng-mocks). Or you might try to create a simple module in the mock-file. Otherwise, I have no idea :)


Post by alex.l »

@juris please let us know if any luck with that! :)

All the best,
Alex


Post by 9ranjeet_prajapati »

Hi Alex,
Same error I am getting for my react application when my pipeline calling npm run test
below is the error


 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from './BryntumFullscreenButton';
                                                                                      ^^^^^^

SyntaxError: Unexpected token 'export'

  1 | import React, { useEffect, useState, useRef } from 'react';
> 2 | import { BryntumSchedulerPro } from "@bryntum/schedulerpro-react";

Post by alex.l »

Hi,

The thread is about Angular. Please create a new thread for your question with more context, if possible share your app or at least attach app configs. Try to check StackOverflow with this problem, that sounds like configuration problem and not our code. But anyway, we are waiting for more details in separated thread.

Thank you!

All the best,
Alex


Post Reply