From 71a4d6dbf510bf2281392c37e30fe9eac6a3b190 Mon Sep 17 00:00:00 2001 From: Eric Peairs Date: Thu, 9 Apr 2026 11:41:06 +0200 Subject: [PATCH 1/3] Refactor tests and add integration tests --- package.json | 42 +- srv/service.js | 8 - tests/bookshop/.gitignore | 34 + tests/bookshop/README.md | 25 + tests/bookshop/app/_i18n/i18n.properties | 29 + tests/bookshop/app/_i18n/i18n_de.properties | 29 + .../app/admin-books/fiori-service.cds | 118 +++ .../app/admin-books/webapp/Component.js | 8 + .../admin-books/webapp/i18n/i18n.properties | 3 + .../webapp/i18n/i18n_de.properties | 3 + .../webapp/i18n/i18n_en.properties | 3 + .../app/admin-books/webapp/manifest.json | 145 +++ .../app/appconfig/fioriSandboxConfig.json | 95 ++ tests/bookshop/app/browse/fiori-service.cds | 57 ++ tests/bookshop/app/browse/webapp/Component.js | 7 + .../app/browse/webapp/i18n/i18n.properties | 4 + .../app/browse/webapp/i18n/i18n_de.properties | 3 + .../app/browse/webapp/i18n/i18n_en.properties | 4 + .../bookshop/app/browse/webapp/manifest.json | 138 +++ tests/bookshop/app/common.cds | 264 ++++++ tests/bookshop/app/index.html | 32 + tests/bookshop/app/services.cds | 6 + .../db/data/sap.capire.bookshop-Authors.csv | 5 + .../db/data/sap.capire.bookshop-Books.csv | 6 + .../data/sap.capire.bookshop-Books_texts.csv | 5 + .../db/data/sap.capire.bookshop-Genres.csv | 16 + tests/bookshop/db/schema.cds | 36 + tests/bookshop/eslint.config.mjs | 2 + tests/bookshop/package.json | 20 + tests/bookshop/srv/admin-service.cds | 6 + tests/bookshop/srv/cat-service.cds | 37 + tests/bookshop/srv/notification-types.json | 16 + tests/integration/bookshop.test.js | 98 +++ tests/lib/content-deployment.test.js | 45 - tests/lib/notificationTypes.test.js | 825 ------------------ tests/lib/notifications.test.js | 150 ---- tests/lib/utils.test.js | 571 ------------ tests/srv/notifyToRest.test.js | 61 -- tests/unit/lib/content-deployment.test.js | 53 ++ tests/unit/lib/notificationTypes.test.js | 684 +++++++++++++++ tests/unit/lib/notifications.test.js | 74 ++ tests/unit/lib/utils.test.js | 476 ++++++++++ tests/unit/srv/notifyToRest.test.js | 91 ++ 43 files changed, 2659 insertions(+), 1675 deletions(-) create mode 100644 tests/bookshop/.gitignore create mode 100644 tests/bookshop/README.md create mode 100644 tests/bookshop/app/_i18n/i18n.properties create mode 100644 tests/bookshop/app/_i18n/i18n_de.properties create mode 100644 tests/bookshop/app/admin-books/fiori-service.cds create mode 100644 tests/bookshop/app/admin-books/webapp/Component.js create mode 100644 tests/bookshop/app/admin-books/webapp/i18n/i18n.properties create mode 100644 tests/bookshop/app/admin-books/webapp/i18n/i18n_de.properties create mode 100644 tests/bookshop/app/admin-books/webapp/i18n/i18n_en.properties create mode 100644 tests/bookshop/app/admin-books/webapp/manifest.json create mode 100644 tests/bookshop/app/appconfig/fioriSandboxConfig.json create mode 100644 tests/bookshop/app/browse/fiori-service.cds create mode 100644 tests/bookshop/app/browse/webapp/Component.js create mode 100644 tests/bookshop/app/browse/webapp/i18n/i18n.properties create mode 100644 tests/bookshop/app/browse/webapp/i18n/i18n_de.properties create mode 100644 tests/bookshop/app/browse/webapp/i18n/i18n_en.properties create mode 100644 tests/bookshop/app/browse/webapp/manifest.json create mode 100644 tests/bookshop/app/common.cds create mode 100644 tests/bookshop/app/index.html create mode 100644 tests/bookshop/app/services.cds create mode 100644 tests/bookshop/db/data/sap.capire.bookshop-Authors.csv create mode 100644 tests/bookshop/db/data/sap.capire.bookshop-Books.csv create mode 100644 tests/bookshop/db/data/sap.capire.bookshop-Books_texts.csv create mode 100644 tests/bookshop/db/data/sap.capire.bookshop-Genres.csv create mode 100644 tests/bookshop/db/schema.cds create mode 100644 tests/bookshop/eslint.config.mjs create mode 100644 tests/bookshop/package.json create mode 100644 tests/bookshop/srv/admin-service.cds create mode 100644 tests/bookshop/srv/cat-service.cds create mode 100644 tests/bookshop/srv/notification-types.json create mode 100644 tests/integration/bookshop.test.js delete mode 100644 tests/lib/content-deployment.test.js delete mode 100644 tests/lib/notificationTypes.test.js delete mode 100644 tests/lib/notifications.test.js delete mode 100644 tests/lib/utils.test.js delete mode 100644 tests/srv/notifyToRest.test.js create mode 100644 tests/unit/lib/content-deployment.test.js create mode 100644 tests/unit/lib/notificationTypes.test.js create mode 100644 tests/unit/lib/notifications.test.js create mode 100644 tests/unit/lib/utils.test.js create mode 100644 tests/unit/srv/notifyToRest.test.js diff --git a/package.json b/package.json index 31f3b2d..f771ce2 100644 --- a/package.json +++ b/package.json @@ -21,10 +21,13 @@ "@sap-cloud-sdk/util": "^3.13.0" }, "devDependencies": { - "jest": "^29.7.0", - "chai": "^4.3.10", + "@cap-js/cds-test": ">=0", + "@cap-js/sqlite": "^2.2.0", "@sap/cds": ">=8.0", - "@sap/cds-dk": ">=8.0" + "@sap/cds-dk": ">=8.0", + "chai": "^4.3.10", + "express": "^5.2.1", + "jest": "^29.7.0" }, "scripts": { "lint": "npx eslint .", @@ -35,17 +38,6 @@ "requires": { "destinations": true, "notifications": { - "[development]": { - "kind": "notify-to-console" - }, - "[hybrid]": { - "destination": "SAP_Notifications", - "kind": "notify-to-rest" - }, - "[production]": { - "destination": "SAP_Notifications", - "kind": "notify-to-rest" - }, "prefix": "$app-name", "types": "srv/notification-types.json", "outbox": true @@ -57,7 +49,27 @@ "notify-to-rest": { "impl": "@cap-js/notifications/srv/notifyToRest" } + }, + "[development]": { + "notifications": { + "kind": "notify-to-console" + } + }, + "[hybrid]": { + "notifications": { + "destination": "SAP_Notifications", + "kind": "notify-to-rest" + } + }, + "[production]": { + "notifications": { + "destination": "SAP_Notifications", + "kind": "notify-to-rest" + } } } - } + }, + "workspaces": [ + "tests/bookshop/" + ] } diff --git a/srv/service.js b/srv/service.js index 41d34bf..8553124 100644 --- a/srv/service.js +++ b/srv/service.js @@ -35,11 +35,3 @@ class NotificationService extends cds.Service { } module.exports = NotificationService - -// Without Generic Outbox only alert.notify() can be used, not alert.emit() -// Remove that when @sap/cds with Generic Outbox is released -if (!cds.outboxed) { - class OutboxedNotificationService extends require('@sap/cds/libx/_runtime/messaging/Outbox') {} - OutboxedNotificationService.prototype.notify = NotificationService.prototype.emit - module.exports = OutboxedNotificationService -} diff --git a/tests/bookshop/.gitignore b/tests/bookshop/.gitignore new file mode 100644 index 0000000..eb69605 --- /dev/null +++ b/tests/bookshop/.gitignore @@ -0,0 +1,34 @@ +# CAP bookshop +_out +*.db +*.sqlite +connection.properties +default-*.json +.cdsrc-private.json +gen/ +node_modules/ +target/ + +# Web IDE, App Studio +.che/ +.gen/ + +# MTA +*_mta_build_tmp +*.mtar +mta_archives/ + +# Other +.DS_Store +*.orig +*.log + +*.iml +*.flattened-pom.xml + +# IDEs +# .vscode +# .idea + +# @cap-js/cds-typer +@cds-models diff --git a/tests/bookshop/README.md b/tests/bookshop/README.md new file mode 100644 index 0000000..dbac29e --- /dev/null +++ b/tests/bookshop/README.md @@ -0,0 +1,25 @@ +# Getting Started + +Welcome to your new project. + +It contains these folders and files, following our recommended project layout: + +File or Folder | Purpose +---------|---------- +`app/` | content for UI frontends goes here +`db/` | your domain models and data go here +`srv/` | your service models and code go here +`package.json` | project metadata and configuration +`readme.md` | this getting started guide + + +## Next Steps + +- Open a new terminal and run `cds watch` +- (in VS Code simply choose _**Terminal** > Run Task > cds watch_) +- Start adding content, for example, a [db/schema.cds](db/schema.cds). + + +## Learn More + +Learn more at https://cap.cloud.sap/docs/get-started/. diff --git a/tests/bookshop/app/_i18n/i18n.properties b/tests/bookshop/app/_i18n/i18n.properties new file mode 100644 index 0000000..597c7e6 --- /dev/null +++ b/tests/bookshop/app/_i18n/i18n.properties @@ -0,0 +1,29 @@ +Books = Books +Book = Book +ID = ID +Title = Title +Author = Author +Authors = Authors +AuthorID = Author ID +AuthorName = Author Name +Name = Name +Age = Age +Stock = Stock +Order = Order +Orders = Orders +Price = Price +Genre = Genre +Genres = Genres +DateOfBirth = Date of Birth +DateOfDeath = Date of Death +PlaceOfBirth = Place of Birth +PlaceOfDeath = Place of Death +Details = Details +Languages = Languages +Currencies = Currencies +MainGenre = Main Genre +SubGenres = Subgenres +Admin = Admin +Translations = Translations +General = General +Locale = Locale diff --git a/tests/bookshop/app/_i18n/i18n_de.properties b/tests/bookshop/app/_i18n/i18n_de.properties new file mode 100644 index 0000000..1b14aba --- /dev/null +++ b/tests/bookshop/app/_i18n/i18n_de.properties @@ -0,0 +1,29 @@ +Books = Bücher +Book = Buch +ID = ID +Title = Titel +Author = Autor +Authors = Autoren +AuthorID = ID des Autors +AuthorName = Name des Autors +Name = Name +Age = Alter +Stock = Bestand +Order = Bestellung +Orders = Bestellungen +Price = Preis +Genre = Genre +Genres = Genres +DateOfBirth = Geburtsdatum +DateOfDeath = Todesdatum +PlaceOfBirth = Geburtsort +PlaceOfDeath = Todesort +Details = Details +Languages = Sprachen +Currencies = Währungen +MainGenre = Hauptgenre +SubGenres = Subgenres +Admin = Admin +Translations = Übersetzungen +General = Allgemein +Locale = Gebietsschema diff --git a/tests/bookshop/app/admin-books/fiori-service.cds b/tests/bookshop/app/admin-books/fiori-service.cds new file mode 100644 index 0000000..200d78f --- /dev/null +++ b/tests/bookshop/app/admin-books/fiori-service.cds @@ -0,0 +1,118 @@ +using {AdminService} from '../../srv/admin-service.cds'; + +//////////////////////////////////////////////////////////////////////////// +// +// Books Object Page +// + +annotate AdminService.Books with @(UI: { + HeaderInfo : { + TypeName : '{i18n>Book}', + TypeNamePlural: '{i18n>Books}', + Title : {Value: title}, + Description : {Value: author.name} + }, + Facets : [ + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>General}', + Target: '@UI.FieldGroup#General' + }, + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Translations}', + Target: 'texts/@UI.LineItem' + }, + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target: '@UI.FieldGroup#Details' + }, + { + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Admin}', + Target: '@UI.FieldGroup#Admin' + }, + ], + FieldGroup #General: {Data: [ + {Value: title}, + {Value: author_ID}, + {Value: genre_ID}, + {Value: descr}, + ]}, + FieldGroup #Details: {Data: [ + {Value: stock}, + {Value: price}, + { + Value: currency_code, + Label: '{i18n>Currency}' + }, + ]}, + FieldGroup #Admin : {Data: [ + {Value: createdBy}, + {Value: createdAt}, + {Value: modifiedBy}, + {Value: modifiedAt} + ]} +}); + + +//////////////////////////////////////////////////////////// +// +// Draft for Localized Data +// + +annotate sap.capire.bookshop.Books with @fiori.draft.enabled; +annotate AdminService.Books with @odata.draft.enabled; + +annotate AdminService.Books.texts with @(UI: { + Identification : [{Value: title}], + SelectionFields: [ + locale, + title + ], + LineItem : [ + { + Value: locale, + Label: '{i18n>Locale}' + }, + { + Value: title, + Label: '{i18n>Title}' + }, + { + Value: descr, + Label: '{i18n>Description}' + }, + ] +}); + +annotate AdminService.Books.texts with { + ID @UI.Hidden; + ID_texts @UI.Hidden; +}; + +// Add Value Help for Locales +annotate AdminService.Books.texts { + locale @( + ValueList.entity: 'Languages', + Common.ValueListWithFixedValues, //show as drop down, not a dialog + ) +}; + +// In addition we need to expose Languages through AdminService as a target for ValueList +using {sap} from '@sap/cds/common'; + +extend service AdminService { + @readonly + entity Languages as projection on sap.common.Languages; +} + +// Workaround for Fiori popups for asking user to enter a valid UUID on Create +annotate AdminService.Authors : ID with @Core.Computed @odata.Type: 'Edm.String'; +annotate AdminService.Books : ID with @Core.Computed @odata.Type: 'Edm.String'; + +// Show Genre as drop down, not a dialog +annotate AdminService.Books with { + genre @Common.ValueListWithFixedValues; +} diff --git a/tests/bookshop/app/admin-books/webapp/Component.js b/tests/bookshop/app/admin-books/webapp/Component.js new file mode 100644 index 0000000..e98677e --- /dev/null +++ b/tests/bookshop/app/admin-books/webapp/Component.js @@ -0,0 +1,8 @@ +sap.ui.define(["sap/fe/core/AppComponent"], function (AppComponent) { + "use strict"; + return AppComponent.extend("books.Component", { + metadata: { manifest: "json" } + }); +}); + +/* eslint no-undef:0 */ diff --git a/tests/bookshop/app/admin-books/webapp/i18n/i18n.properties b/tests/bookshop/app/admin-books/webapp/i18n/i18n.properties new file mode 100644 index 0000000..9a23ee4 --- /dev/null +++ b/tests/bookshop/app/admin-books/webapp/i18n/i18n.properties @@ -0,0 +1,3 @@ +appTitle=Manage Books +appSubTitle=Manage bookshop inventory +appDescription=Manage your bookshop inventory with ease. diff --git a/tests/bookshop/app/admin-books/webapp/i18n/i18n_de.properties b/tests/bookshop/app/admin-books/webapp/i18n/i18n_de.properties new file mode 100644 index 0000000..668c976 --- /dev/null +++ b/tests/bookshop/app/admin-books/webapp/i18n/i18n_de.properties @@ -0,0 +1,3 @@ +appTitle=Bücher verwalten +appSubTitle=Verwalten Sie den Bestand der Buchhandlung +appDescription=Verwalten Sie den Bestand Ihrer Buchhandlung ganz einfach. diff --git a/tests/bookshop/app/admin-books/webapp/i18n/i18n_en.properties b/tests/bookshop/app/admin-books/webapp/i18n/i18n_en.properties new file mode 100644 index 0000000..9a23ee4 --- /dev/null +++ b/tests/bookshop/app/admin-books/webapp/i18n/i18n_en.properties @@ -0,0 +1,3 @@ +appTitle=Manage Books +appSubTitle=Manage bookshop inventory +appDescription=Manage your bookshop inventory with ease. diff --git a/tests/bookshop/app/admin-books/webapp/manifest.json b/tests/bookshop/app/admin-books/webapp/manifest.json new file mode 100644 index 0000000..13d7c49 --- /dev/null +++ b/tests/bookshop/app/admin-books/webapp/manifest.json @@ -0,0 +1,145 @@ +{ + "_version": "1.49.0", + "sap.app": { + "id": "bookshop.admin-books", + "applicationVersion": { + "version": "1.0.0" + }, + "type": "application", + "title": "{{appTitle}}", + "description": "{{appDescription}}", + "i18n": "i18n/i18n.properties", + "dataSources": { + "AdminService": { + "uri": "odata/v4/admin/", + "type": "OData", + "settings": { + "odataVersion": "4.0" + } + } + }, + "crossNavigation": { + "inbounds": { + "intent-Books-manage": { + "signature": { + "parameters": {}, + "additionalParameters": "allowed" + }, + "semanticObject": "Books", + "action": "manage" + } + } + } + }, + "sap.ui": { + "technology": "UI5", + "fullWidth": false, + "deviceTypes": { + "desktop": true, + "tablet": true, + "phone": true + } + }, + "sap.ui5": { + "dependencies": { + "minUI5Version": "1.115.1", + "libs": { + "sap.fe.templates": {} + } + }, + "models": { + "i18n": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/i18n.properties" + }, + "": { + "dataSource": "AdminService", + "settings": { + "operationMode": "Server", + "autoExpandSelect": true, + "earlyRequests": true, + "groupProperties": { + "default": { + "submit": "Auto" + } + } + } + } + }, + "routing": { + "routes": [ + { + "pattern": ":?query:", + "name": "BooksList", + "target": "BooksList" + }, + { + "pattern": "Books({key}):?query:", + "name": "BooksDetails", + "target": "BooksDetails" + }, + { + "pattern": "Books({key}/author({key2}):?query:", + "name": "AuthorsDetails", + "target": "AuthorsDetails" + } + ], + "targets": { + "BooksList": { + "type": "Component", + "id": "BooksList", + "name": "sap.fe.templates.ListReport", + "options": { + "settings": { + "entitySet": "Books", + "initialLoad": true, + "navigation": { + "Books": { + "detail": { + "route": "BooksDetails" + } + } + } + } + } + }, + "BooksDetails": { + "type": "Component", + "id": "BooksDetailsList", + "name": "sap.fe.templates.ObjectPage", + "options": { + "settings": { + "entitySet": "Books", + "editableHeaderContent": false, + "navigation": { + "Authors": { + "detail": { + "route": "AuthorsDetails" + } + } + } + } + } + }, + "AuthorsDetails": { + "type": "Component", + "id": "AuthorsDetailsList", + "name": "sap.fe.templates.ObjectPage", + "options": { + "settings": { + "entitySet": "Authors" + } + } + } + } + }, + "contentDensities": { + "compact": true, + "cozy": true + } + }, + "sap.fiori": { + "registrationIds": [], + "archeType": "transactional" + } +} diff --git a/tests/bookshop/app/appconfig/fioriSandboxConfig.json b/tests/bookshop/app/appconfig/fioriSandboxConfig.json new file mode 100644 index 0000000..ff2ac49 --- /dev/null +++ b/tests/bookshop/app/appconfig/fioriSandboxConfig.json @@ -0,0 +1,95 @@ +{ + "services": { + "LaunchPage": { + "adapter": { + "config": { + "catalogs": [], + "groups": [ + { + "id": "Bookshop", + "title": "Bookshop", + "isPreset": true, + "isVisible": true, + "isGroupLocked": false, + "tiles": [ + { + "id": "BrowseBooks", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Browse Books", + "targetURL": "#Books-display" + } + } + ] + }, + { + "id": "Administration", + "title": "Administration", + "isPreset": true, + "isVisible": true, + "isGroupLocked": false, + "tiles": [ + { + "id": "ManageBooks", + "tileType": "sap.ushell.ui.tile.StaticTile", + "properties": { + "title": "Manage Books", + "targetURL": "#Books-manage" + } + } + ] + } + ] + } + } + }, + "NavTargetResolution": { + "config": { + "enableClientSideTargetResolution": true + } + }, + "ClientSideTargetResolution": { + "adapter": { + "config": { + "inbounds": { + "BrowseBooks": { + "semanticObject": "Books", + "action": "display", + "title": "Browse Books", + "signature": { + "parameters": { + "Books.ID": { + "renameTo": "ID" + }, + "Authors.books.ID": { + "renameTo": "ID" + } + }, + "additionalParameters": "ignored" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=bookshop", + "url": "browse/webapp" + } + }, + "ManageBooks": { + "semanticObject": "Books", + "action": "manage", + "title": "Manage Books", + "signature": { + "parameters": {}, + "additionalParameters": "allowed" + }, + "resolutionResult": { + "applicationType": "SAPUI5", + "additionalInformation": "SAPUI5.Component=books", + "url": "admin-books/webapp" + } + } + } + } + } + } + } +} diff --git a/tests/bookshop/app/browse/fiori-service.cds b/tests/bookshop/app/browse/fiori-service.cds new file mode 100644 index 0000000..1397a60 --- /dev/null +++ b/tests/bookshop/app/browse/fiori-service.cds @@ -0,0 +1,57 @@ +using {CatalogService} from '../../srv/cat-service.cds'; + +//////////////////////////////////////////////////////////////////////////// +// +// Books Object Page +// +annotate CatalogService.Books with @(UI: { + HeaderInfo : { + TypeName : '{i18n>Book}', + TypeNamePlural: '{i18n>Books}', + Title : {Value: title}, + Description : {Value: author} + }, + HeaderFacets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Description}', + Target: '@UI.FieldGroup#Descr' + }, ], + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target: '@UI.FieldGroup#Price' + }, ], + FieldGroup #Descr: {Data: [{Value: descr}, ]}, + FieldGroup #Price: {Data: [ + {Value: price}, + { + Value: currency.symbol, + Label: '{i18n>Currency}' + }, + ]}, +}); + +//////////////////////////////////////////////////////////////////////////// +// +// Books List Page +// +annotate CatalogService.Books with @(UI: { + SelectionFields: [ + ID, + price, + currency_code + ], + LineItem : [ + { + Value: ID, + Label: '{i18n>Title}' + }, + { + Value: author, + Label: '{i18n>Author}' + }, + {Value: genre.name}, + {Value: price}, + {Value: currency.symbol}, + ] +}); diff --git a/tests/bookshop/app/browse/webapp/Component.js b/tests/bookshop/app/browse/webapp/Component.js new file mode 100644 index 0000000..4020679 --- /dev/null +++ b/tests/bookshop/app/browse/webapp/Component.js @@ -0,0 +1,7 @@ +sap.ui.define(["sap/fe/core/AppComponent"], function(AppComponent) { + "use strict"; + return AppComponent.extend("bookshop.Component", { + metadata: { manifest: "json" } + }); +}); +/* eslint no-undef:0 */ diff --git a/tests/bookshop/app/browse/webapp/i18n/i18n.properties b/tests/bookshop/app/browse/webapp/i18n/i18n.properties new file mode 100644 index 0000000..05d21aa --- /dev/null +++ b/tests/bookshop/app/browse/webapp/i18n/i18n.properties @@ -0,0 +1,4 @@ +appTitle=Browse Books +appSubTitle=All books in one place +appDescription=This application lets you find the next books you want to read. +appInfo=Find your favorite books diff --git a/tests/bookshop/app/browse/webapp/i18n/i18n_de.properties b/tests/bookshop/app/browse/webapp/i18n/i18n_de.properties new file mode 100644 index 0000000..ea86c3f --- /dev/null +++ b/tests/bookshop/app/browse/webapp/i18n/i18n_de.properties @@ -0,0 +1,3 @@ +appTitle=Bücher anschauen +appSubTitle=Finden sie ihre nächste Lektüre +appDescription=Finden Sie die nachsten Bücher, die Sie lesen möchten. diff --git a/tests/bookshop/app/browse/webapp/i18n/i18n_en.properties b/tests/bookshop/app/browse/webapp/i18n/i18n_en.properties new file mode 100644 index 0000000..05d21aa --- /dev/null +++ b/tests/bookshop/app/browse/webapp/i18n/i18n_en.properties @@ -0,0 +1,4 @@ +appTitle=Browse Books +appSubTitle=All books in one place +appDescription=This application lets you find the next books you want to read. +appInfo=Find your favorite books diff --git a/tests/bookshop/app/browse/webapp/manifest.json b/tests/bookshop/app/browse/webapp/manifest.json new file mode 100644 index 0000000..3a33dab --- /dev/null +++ b/tests/bookshop/app/browse/webapp/manifest.json @@ -0,0 +1,138 @@ +{ + "_version": "1.49.0", + "sap.app": { + "id": "bookshop.browse", + "applicationVersion": { + "version": "1.0.0" + }, + "type": "application", + "title": "{{appTitle}}", + "description": "{{appDescription}}", + "i18n": "i18n/i18n.properties", + "dataSources": { + "CatalogService": { + "uri": "odata/v4/catalog/", + "type": "OData", + "settings": { + "odataVersion": "4.0" + } + } + }, + "crossNavigation": { + "inbounds": { + "Books-display": { + "signature": { + "parameters": { + "Books.ID": { + "renameTo": "ID" + }, + "Authors.books.ID": { + "renameTo": "ID" + } + }, + "additionalParameters": "allowed" + }, + "semanticObject": "Books", + "action": "display", + "title": "{{appTitle}}", + "info": "{{appInfo}}", + "subTitle": "{{appSubTitle}}", + "icon": "sap-icon://course-book", + "indicatorDataSource": { + "dataSource": "CatalogService", + "path": "Books/$count", + "refresh": 1800 + } + } + } + } + }, + "sap.ui": { + "technology": "UI5", + "fullWidth": false, + "deviceTypes": { + "desktop": true, + "tablet": true, + "phone": true + } + }, + "sap.ui5": { + "dependencies": { + "minUI5Version": "1.115.1", + "libs": { + "sap.fe.templates": {} + } + }, + "models": { + "i18n": { + "type": "sap.ui.model.resource.ResourceModel", + "uri": "i18n/i18n.properties" + }, + "": { + "dataSource": "CatalogService", + "settings": { + "operationMode": "Server", + "autoExpandSelect": true, + "earlyRequests": true, + "groupProperties": { + "default": { + "submit": "Auto" + } + } + } + } + }, + "routing": { + "routes": [ + { + "pattern": ":?query:", + "name": "BooksList", + "target": "BooksList" + }, + { + "pattern": "Books({key}):?query:", + "name": "BooksDetails", + "target": "BooksDetails" + } + ], + "targets": { + "BooksList": { + "type": "Component", + "id": "BooksList", + "name": "sap.fe.templates.ListReport", + "options": { + "settings": { + "entitySet": "Books", + "initialLoad": true, + "navigation": { + "Books": { + "detail": { + "route": "BooksDetails" + } + } + } + } + } + }, + "BooksDetails": { + "type": "Component", + "id": "BooksDetailsList", + "name": "sap.fe.templates.ObjectPage", + "options": { + "settings": { + "entitySet": "Books" + } + } + } + } + }, + "contentDensities": { + "compact": true, + "cozy": true + } + }, + "sap.fiori": { + "registrationIds": [], + "archeType": "transactional" + } +} diff --git a/tests/bookshop/app/common.cds b/tests/bookshop/app/common.cds new file mode 100644 index 0000000..3ef5b23 --- /dev/null +++ b/tests/bookshop/app/common.cds @@ -0,0 +1,264 @@ +/* + Common Annotations shared by all apps +*/ + +using {sap.capire.bookshop as my} from '../db/schema'; +using { + sap.common, + sap.common.Currencies +} from '@sap/cds/common'; + +//////////////////////////////////////////////////////////////////////////// +// +// Books Lists +// +annotate my.Books with @( + Common.SemanticKey: [ID], + UI : { + Identification : [{Value: title}], + SelectionFields: [ + ID, + author_ID, + price, + currency_code + ], + LineItem : [ + { + Value: ID, + Label: '{i18n>Title}' + }, + { + Value: author.ID, + Label: '{i18n>Author}' + }, + {Value: genre.name}, + {Value: stock}, + {Value: price}, + {Value: currency.symbol}, + ] + } +) { + ID @Common : { + SemanticObject : 'Books', + Text : title, + TextArrangement: #TextOnly + }; + author @ValueList.entity: 'Authors'; +}; + +annotate Currencies with { + symbol @Common.Label: '{i18n>Currency}'; +} + + +//////////////////////////////////////////////////////////////////////////// +// +// Books Elements +// +annotate my.Books with { + ID @title: '{i18n>ID}'; + title @title: '{i18n>Title}'; + genre @title: '{i18n>Genre}' @Common : { + Text : genre.name, + TextArrangement: #TextOnly + }; + author @title: '{i18n>Author}' @Common : { + Text : author.name, + TextArrangement: #TextOnly + }; + price @title: '{i18n>Price}' @Measures.ISOCurrency: currency_code; + stock @title: '{i18n>Stock}'; + descr @title: '{i18n>Description}' @UI.MultiLineText; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Genres List +// +annotate my.Genres with @( + Common.SemanticKey: [name], + UI : { + SelectionFields: [name], + LineItem : [ + {Value: name}, + { + Value: parent.name, + Label: '{i18n>MainGenre}' + }, + ], + } +); + +annotate my.Genres with { + ID @Common.Text: name @Common.TextArrangement: #TextOnly; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Genre Details +// +annotate my.Genres with @(UI: { + Identification: [{Value: name}], + HeaderInfo : { + TypeName : '{i18n>Genre}', + TypeNamePlural: '{i18n>Genres}', + Title : {Value: name}, + Description : {Value: ID} + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>SubGenres}', + Target: 'children/@UI.LineItem' + }, ], +}); + +//////////////////////////////////////////////////////////////////////////// +// +// Genres Elements +// +annotate my.Genres with { + ID @title: '{i18n>ID}'; + name @title: '{i18n>Genre}'; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Authors List +// +annotate my.Authors with @( + Common.SemanticKey: [ID], + UI : { + Identification : [{Value: name}], + SelectionFields: [name], + LineItem : [ + {Value: ID}, + {Value: dateOfBirth}, + {Value: dateOfDeath}, + {Value: placeOfBirth}, + {Value: placeOfDeath}, + ], + } +) { + ID @Common: { + SemanticObject : 'Authors', + Text : name, + TextArrangement: #TextOnly, + }; +}; + +//////////////////////////////////////////////////////////////////////////// +// +// Author Details +// +annotate my.Authors with @(UI: { + HeaderInfo: { + TypeName : '{i18n>Author}', + TypeNamePlural: '{i18n>Authors}', + Title : {Value: name}, + Description : {Value: dateOfBirth} + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Target: 'books/@UI.LineItem' + }], +}); + + +//////////////////////////////////////////////////////////////////////////// +// +// Authors Elements +// +annotate my.Authors with { + ID @title: '{i18n>ID}'; + name @title: '{i18n>Name}'; + dateOfBirth @title: '{i18n>DateOfBirth}'; + dateOfDeath @title: '{i18n>DateOfDeath}'; + placeOfBirth @title: '{i18n>PlaceOfBirth}'; + placeOfDeath @title: '{i18n>PlaceOfDeath}'; +} + +//////////////////////////////////////////////////////////////////////////// +// +// Languages List +// +annotate common.Languages with @( + Common.SemanticKey: [code], + Identification : [{Value: code}], + UI : { + SelectionFields: [ + name, + descr + ], + LineItem : [ + {Value: code}, + {Value: name}, + ], + } +); + +//////////////////////////////////////////////////////////////////////////// +// +// Language Details +// +annotate common.Languages with @(UI: { + HeaderInfo : { + TypeName : '{i18n>Language}', + TypeNamePlural: '{i18n>Languages}', + Title : {Value: name}, + Description : {Value: descr} + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target: '@UI.FieldGroup#Details' + }, ], + FieldGroup #Details: {Data: [ + {Value: code}, + {Value: name}, + {Value: descr} + ]}, +}); + +//////////////////////////////////////////////////////////////////////////// +// +// Currencies List +// +annotate common.Currencies with @( + Common.SemanticKey: [code], + Identification : [{Value: code}], + UI : { + SelectionFields: [ + name, + descr + ], + LineItem : [ + {Value: descr}, + {Value: symbol}, + {Value: code}, + ], + } +); + +//////////////////////////////////////////////////////////////////////////// +// +// Currency Details +// +annotate common.Currencies with @(UI: { + HeaderInfo : { + TypeName : '{i18n>Currency}', + TypeNamePlural: '{i18n>Currencies}', + Title : {Value: descr}, + Description : {Value: code} + }, + Facets : [{ + $Type : 'UI.ReferenceFacet', + Label : '{i18n>Details}', + Target: '@UI.FieldGroup#Details' + }], + FieldGroup #Details: {Data: [ + {Value: name}, + {Value: symbol}, + {Value: code}, + {Value: descr} + ]} +}); diff --git a/tests/bookshop/app/index.html b/tests/bookshop/app/index.html new file mode 100644 index 0000000..6676bd4 --- /dev/null +++ b/tests/bookshop/app/index.html @@ -0,0 +1,32 @@ + + + + + + + + Bookshop + + + + + + + + + + diff --git a/tests/bookshop/app/services.cds b/tests/bookshop/app/services.cds new file mode 100644 index 0000000..87e7b31 --- /dev/null +++ b/tests/bookshop/app/services.cds @@ -0,0 +1,6 @@ +/* + This model controls what gets served to Fiori frontends... +*/ +using from './common'; +using from './browse/fiori-service'; +using from './admin-books/fiori-service'; diff --git a/tests/bookshop/db/data/sap.capire.bookshop-Authors.csv b/tests/bookshop/db/data/sap.capire.bookshop-Authors.csv new file mode 100644 index 0000000..9b418c1 --- /dev/null +++ b/tests/bookshop/db/data/sap.capire.bookshop-Authors.csv @@ -0,0 +1,5 @@ +ID,name,dateOfBirth,placeOfBirth,dateOfDeath,placeOfDeath +101,Emily Brontë,1818-07-30,"Thornton, Yorkshire",1848-12-19,"Haworth, Yorkshire" +107,Charlotte Brontë,1818-04-21,"Thornton, Yorkshire",1855-03-31,"Haworth, Yorkshire" +150,Edgar Allen Poe,1809-01-19,"Boston, Massachusetts",1849-10-07,"Baltimore, Maryland" +170,Richard Carpenter,1929-08-14,"King’s Lynn, Norfolk",2012-02-26,"Hertfordshire, England" diff --git a/tests/bookshop/db/data/sap.capire.bookshop-Books.csv b/tests/bookshop/db/data/sap.capire.bookshop-Books.csv new file mode 100644 index 0000000..fa6cca8 --- /dev/null +++ b/tests/bookshop/db/data/sap.capire.bookshop-Books.csv @@ -0,0 +1,6 @@ +ID,title,descr,author_ID,stock,price,currency_code,genre_ID +201,Wuthering Heights,"Wuthering Heights, Emily Brontë's only novel, was published in 1847 under the pseudonym ""Ellis Bell"". It was written between October 1845 and June 1846. Wuthering Heights and Anne Brontë's Agnes Grey were accepted by publisher Thomas Newby before the success of their sister Charlotte's novel Jane Eyre. After Emily's death, Charlotte edited the manuscript of Wuthering Heights and arranged for the edited version to be published as a posthumous second edition in 1850.",101,12,11.11,GBP,11 +207,Jane Eyre,"Jane Eyre /ɛər/ (originally published as Jane Eyre: An Autobiography) is a novel by English writer Charlotte Brontë, published under the pen name ""Currer Bell"", on 16 October 1847, by Smith, Elder & Co. of London. The first American edition was published the following year by Harper & Brothers of New York. Primarily a bildungsroman, Jane Eyre follows the experiences of its eponymous heroine, including her growth to adulthood and her love for Mr. Rochester, the brooding master of Thornfield Hall. The novel revolutionised prose fiction in that the focus on Jane's moral and spiritual development is told through an intimate, first-person narrative, where actions and events are coloured by a psychological intensity. The book contains elements of social criticism, with a strong sense of Christian morality at its core and is considered by many to be ahead of its time because of Jane's individualistic character and how the novel approaches the topics of class, sexuality, religion and feminism.",107,11,12.34,GBP,11 +251,The Raven,"""The Raven"" is a narrative poem by American writer Edgar Allan Poe. First published in January 1845, the poem is often noted for its musicality, stylized language, and supernatural atmosphere. It tells of a talking raven's mysterious visit to a distraught lover, tracing the man's slow fall into madness. The lover, often identified as being a student, is lamenting the loss of his love, Lenore. Sitting on a bust of Pallas, the raven seems to further distress the protagonist with its constant repetition of the word ""Nevermore"". The poem makes use of folk, mythological, religious, and classical references.",150,333,13.13,USD,16 +252,Eleonora,"""Eleonora"" is a short story by Edgar Allan Poe, first published in 1842 in Philadelphia in the literary annual The Gift. It is often regarded as somewhat autobiographical and has a relatively ""happy"" ending.",150,555,14,USD,16 +271,Catweazle,"Catweazle is a British fantasy television series, starring Geoffrey Bayldon in the title role, and created by Richard Carpenter for London Weekend Television. The first series, produced and directed by Quentin Lawrence, was screened in the UK on ITV in 1970. The second series, directed by David Reid and David Lane, was shown in 1971. Each series had thirteen episodes, most but not all written by Carpenter, who also published two books based on the scripts.",170,22,150,JPY,13 diff --git a/tests/bookshop/db/data/sap.capire.bookshop-Books_texts.csv b/tests/bookshop/db/data/sap.capire.bookshop-Books_texts.csv new file mode 100644 index 0000000..b2c4e11 --- /dev/null +++ b/tests/bookshop/db/data/sap.capire.bookshop-Books_texts.csv @@ -0,0 +1,5 @@ +ID_texts,ID,locale,title,descr +52eee553-266d-4fdd-a5ca-909910e76ae4,201,de,Sturmhöhe,"Sturmhöhe (Originaltitel: Wuthering Heights) ist der einzige Roman der englischen Schriftstellerin Emily Brontë (1818–1848). Der 1847 unter dem Pseudonym Ellis Bell veröffentlichte Roman wurde vom viktorianischen Publikum weitgehend abgelehnt, heute gilt er als ein Klassiker der britischen Romanliteratur des 19. Jahrhunderts." +54e58142-f06e-49c1-a51d-138f86cea34e,201,fr,Les Hauts de Hurlevent,"Les Hauts de Hurlevent (titre original : Wuthering Heights), parfois orthographié Les Hauts de Hurle-Vent, est l'unique roman d'Emily Brontë, publié pour la première fois en 1847 sous le pseudonyme d’Ellis Bell. Loin d'être un récit moralisateur, Emily Brontë achève néanmoins le roman dans une atmosphère sereine, suggérant le triomphe de la paix et du Bien sur la vengeance et le Mal." +bbbf8a88-797d-4790-af1c-1cc857718ee0,207,de,Jane Eyre,"Jane Eyre. Eine Autobiographie (Originaltitel: Jane Eyre. An Autobiography), erstmals erschienen im Jahr 1847 unter dem Pseudonym Currer Bell, ist der erste veröffentlichte Roman der britischen Autorin Charlotte Brontë und ein Klassiker der viktorianischen Romanliteratur des 19. Jahrhunderts. Der Roman erzählt in Form einer Ich-Erzählung die Lebensgeschichte von Jane Eyre (ausgesprochen /ˌdʒeɪn ˈɛə/), die nach einer schweren Kindheit eine Stelle als Gouvernante annimmt und sich in ihren Arbeitgeber verliebt, jedoch immer wieder um ihre Freiheit und Selbstbestimmung kämpfen muss. Als klein, dünn, blass, stets schlicht dunkel gekleidet und mit strengem Mittelscheitel beschrieben, gilt die Heldin des Romans Jane Eyre nicht zuletzt aufgrund der Kino- und Fernsehversionen der melodramatischen Romanvorlage als die bekannteste englische Gouvernante der Literaturgeschichte" +a90d4378-1a3e-48e7-b60b-5670e78807e1,252,de,Eleonora,“Eleonora” ist eine Erzählung von Edgar Allan Poe. Sie wurde 1841 erstveröffentlicht. In ihr geht es um das Paradox der Treue in der Treulosigkeit. diff --git a/tests/bookshop/db/data/sap.capire.bookshop-Genres.csv b/tests/bookshop/db/data/sap.capire.bookshop-Genres.csv new file mode 100644 index 0000000..a3070fa --- /dev/null +++ b/tests/bookshop/db/data/sap.capire.bookshop-Genres.csv @@ -0,0 +1,16 @@ +ID,parent_ID,name +10,,Fiction +11,10,Drama +12,10,Poetry +13,10,Fantasy +14,10,Science Fiction +15,10,Romance +16,10,Mystery +17,10,Thriller +18,10,Dystopia +19,10,Fairy Tale +20,,Non-Fiction +21,20,Biography +22,21,Autobiography +23,20,Essay +24,20,Speech diff --git a/tests/bookshop/db/schema.cds b/tests/bookshop/db/schema.cds new file mode 100644 index 0000000..4b596ab --- /dev/null +++ b/tests/bookshop/db/schema.cds @@ -0,0 +1,36 @@ +using { + Currency, + managed, + cuid, + sap +} from '@sap/cds/common'; + +namespace sap.capire.bookshop; + +entity Books : managed, cuid { + title : localized String(111) @mandatory; + descr : localized String(1111); + author : Association to Authors @mandatory; + genre : Association to Genres; + stock : Integer; + price : Decimal; + currency : Currency; +} + +entity Authors : managed, cuid { + name : String(111) @mandatory; + dateOfBirth : Date; + dateOfDeath : Date; + placeOfBirth : String; + placeOfDeath : String; + books : Association to many Books + on books.author = $self; +} + +/** Hierarchically organized Code List for Genres */ +entity Genres : sap.common.CodeList { + key ID : Integer; + parent : Association to Genres; + children : Composition of many Genres + on children.parent = $self; +} diff --git a/tests/bookshop/eslint.config.mjs b/tests/bookshop/eslint.config.mjs new file mode 100644 index 0000000..2fdb432 --- /dev/null +++ b/tests/bookshop/eslint.config.mjs @@ -0,0 +1,2 @@ +import cds from '@sap/cds/eslint.config.mjs' +export default [ ...cds.recommended ] diff --git a/tests/bookshop/package.json b/tests/bookshop/package.json new file mode 100644 index 0000000..69c61ed --- /dev/null +++ b/tests/bookshop/package.json @@ -0,0 +1,20 @@ +{ + "name": "bookshop", + "version": "1.0.0", + "description": "A simple CAP project.", + "dependencies": { + "@cap-js/notifications": "file:../.." + }, + "scripts": { + "start": "cds-serve" + }, + "cds": { + "requires": { + "notifications": { + "outbox": false, + "types": "tests/bookshop/srv/notification-types.json" + } + } + }, + "private": true +} diff --git a/tests/bookshop/srv/admin-service.cds b/tests/bookshop/srv/admin-service.cds new file mode 100644 index 0000000..9ae8bbc --- /dev/null +++ b/tests/bookshop/srv/admin-service.cds @@ -0,0 +1,6 @@ +using {sap.capire.bookshop as my} from '../db/schema'; + +service AdminService @(requires: 'admin') { + entity Books as projection on my.Books; + entity Authors as projection on my.Authors; +} diff --git a/tests/bookshop/srv/cat-service.cds b/tests/bookshop/srv/cat-service.cds new file mode 100644 index 0000000..a24828d --- /dev/null +++ b/tests/bookshop/srv/cat-service.cds @@ -0,0 +1,37 @@ +using {sap.capire.bookshop as my} from '../db/schema'; + +service CatalogService { + + /** For displaying lists of Books */ + @readonly + entity ListOfBooks as + projection on Books + excluding { + descr + }; + + /** For display in details pages */ + @readonly + entity Books as + projection on my.Books { + *, + author.name as author + } + excluding { + createdBy, + modifiedBy + }; + + @requires: 'authenticated-user' + action submitOrder(book : Books : ID @mandatory, + quantity : Integer @mandatory + ) returns { + stock : Integer + }; + + event OrderedBook : { + book : Books : ID; + quantity : Integer; + buyer : String + }; +} diff --git a/tests/bookshop/srv/notification-types.json b/tests/bookshop/srv/notification-types.json new file mode 100644 index 0000000..5bba84b --- /dev/null +++ b/tests/bookshop/srv/notification-types.json @@ -0,0 +1,16 @@ +[ + { + "NotificationTypeKey": "BookOrdered", + "NotificationTypeVersion": "1", + "Templates": [ + { + "Language": "en", + "TemplatePublic": "Book Ordered", + "TemplateSensitive": "Book '{{title}}' Ordered", + "TemplateGrouped": "Bookshop Updates", + "TemplateLanguage": "mustache", + "Subtitle": "{{buyer}} ordered {{title}}" + } + ] + } +] \ No newline at end of file diff --git a/tests/integration/bookshop.test.js b/tests/integration/bookshop.test.js new file mode 100644 index 0000000..df0d52f --- /dev/null +++ b/tests/integration/bookshop.test.js @@ -0,0 +1,98 @@ +const cds = require("@sap/cds"); +const { join } = cds.utils.path; +const { messages } = require("../../lib/utils"); + +const { } = cds.test(join(__dirname, "../bookshop")); + +describe("Notifications Integration", () => { + // Boot the bookshop app with the plugin active before all tests + let alert; + let infoSpy; + let warnSpy; + + beforeAll(async () => { + alert = await cds.connect.to("notifications"); + }); + + beforeEach(() => { + infoSpy = jest.spyOn(global.console, "info"); + warnSpy = jest.spyOn(global.console, "warn"); + }); + + afterEach(() => { + infoSpy.mockRestore(); + warnSpy.mockRestore(); + }); + + test("Notifications service resolves to console implementation in development", async () => { + expect(alert.constructor.name).toBe("NotifyToConsole"); + }); + + test("Notification types are loaded into cds.notifications on startup", () => { + expect(cds.notifications?.local?.types).toBeDefined(); + expect(cds.notifications.local.types).toHaveProperty("bookshop/BookOrdered"); + }); + + test("Sending a notification with unknown type key gives a warning", async () => { + await alert.notify("UnknownType", { + recipients: ["reader@bookshop.com"], + data: { title: "test" } + }); + + expect(warnSpy).toHaveBeenCalledWith( + "[notifications] -", + expect.stringContaining("UnknownType is not in the notification types file") + ); + }); + + test("Sending a default notification logs to console", async () => { + await alert.notify({ + recipients: ["reader@bookshop.com"], + title: "New book arrived", + description: "A new book has been added to the catalogue" + }); + + expect(infoSpy).toHaveBeenCalledWith( + "[notifications] -", + expect.any(String), + expect.any(String), + expect.objectContaining({ + NotificationTypeKey: "Default", + Priority: "NEUTRAL", + Recipients: [{ RecipientId: "reader@bookshop.com" }], + Properties: expect.arrayContaining([ + expect.objectContaining({ Key: "title", Value: "New book arrived" }) + ]) + }), + expect.any(String) + ); + }); + + test("Sending a notification with no arguments warns and does nothing", async () => { + await alert.notify(); + + expect(warnSpy).toHaveBeenCalledWith( + "[notifications] -", + messages.NO_OBJECT_FOR_NOTIFY + ); + expect(infoSpy).not.toHaveBeenCalled(); + }); + + test("Custom typed notification uses prefixed type key from types file", async () => { + await alert.notify("BookOrdered", { + recipients: ["reader@bookshop.com"], + data: { title: "Moby Dick", buyer: "reader@bookshop.com" } + }); + + expect(infoSpy).toHaveBeenCalledWith( + "[notifications] -", + expect.any(String), + expect.any(String), + expect.objectContaining({ + NotificationTypeKey: "bookshop/BookOrdered" + }), + expect.any(String) + ); + expect(warnSpy).not.toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/tests/lib/content-deployment.test.js b/tests/lib/content-deployment.test.js deleted file mode 100644 index b893b73..0000000 --- a/tests/lib/content-deployment.test.js +++ /dev/null @@ -1,45 +0,0 @@ -// import required modules and functions -const { validateNotificationTypes, readFile } = require("../../lib/utils"); -const { processNotificationTypes } = require("../../lib/notificationTypes"); -const { setGlobalLogLevel } = require("@sap-cloud-sdk/util"); -const assert = require("chai"); - -jest.mock("../../lib/utils"); -jest.mock("../../lib/notificationTypes"); -jest.mock("@sap-cloud-sdk/util"); - -const contentDeployment = require("../../lib/content-deployment"); - -describe("contentDeployment", () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - test("Given valid notification types | When Deploy is called | Then process is called", async () => { - setGlobalLogLevel.mockImplementation(() => undefined); - readFile.mockImplementation(() => []); - validateNotificationTypes.mockImplementation(() => true); - processNotificationTypes.mockImplementation(() => Promise.resolve()); - - await contentDeployment.deployNotificationTypes(); - - console.log(setGlobalLogLevel.mock.calls); - assert.expect(setGlobalLogLevel.mock.calls[0][0]).to.be.equal("error"); - assert.expect(validateNotificationTypes.mock.calls[0][0]).to.be.deep.equal([]); - assert.expect(processNotificationTypes.mock.calls[0][0]).to.be.deep.equal([]); - }); - - test("Given invalid notification types | When Deploy is called | Then process is called", async () => { - setGlobalLogLevel.mockImplementation(() => undefined); - readFile.mockImplementation(() => []); - validateNotificationTypes.mockImplementation(() => false); - processNotificationTypes.mockImplementation(() => Promise.resolve()); - - await contentDeployment.deployNotificationTypes(); - - console.log(setGlobalLogLevel.mock.calls); - assert.expect(setGlobalLogLevel.mock.calls[0][0]).to.be.equal("error"); - assert.expect(validateNotificationTypes.mock.calls[0][0]).to.be.deep.equal([]); - assert.expect(processNotificationTypes.mock.calls[0]).to.be.deep.equal(undefined); - }); -}); diff --git a/tests/lib/notificationTypes.test.js b/tests/lib/notificationTypes.test.js deleted file mode 100644 index 40eccef..0000000 --- a/tests/lib/notificationTypes.test.js +++ /dev/null @@ -1,825 +0,0 @@ -const utils = require("../../lib/utils"); -const httpClient = require("@sap-cloud-sdk/http-client"); -const connectivity = require("@sap-cloud-sdk/connectivity"); -const notificationTypes = require("../../lib/notificationTypes"); -const assert = require("chai"); - -jest.mock("../../lib/utils"); -jest.mock("@sap-cloud-sdk/http-client"); -jest.mock("@sap-cloud-sdk/connectivity"); - -describe("Managing of Notification Types", () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - test("Given 2 New Notification Types and 0 Existing Notification Types | When process is called | Than Default and 2 New Notification Types are created", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(emptyResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - // REVISIT: Never test internal APIs -> blocks us from refactoring - utils.getPrefix.mockReturnValue(testPrefix); - - notificationTypes.processNotificationTypes([copy(notificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.be.equal("get"); - - const createDefaultNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(createDefaultNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes"); - assert.expect(createDefaultNotificationType.method).to.be.equal("post"); - assert.expect(createDefaultNotificationType.data).to.be.deep.equal(defaultNotificationType); - - const createFirstNotificationType = httpClient.executeHttpRequest.mock.calls[2][1]; - assert.expect(createFirstNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes"); - assert.expect(createFirstNotificationType.method).to.be.equal("post"); - assert.expect(createFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(notificationTypeWithAllProperties)); - - const createSecondNotificationType = httpClient.executeHttpRequest.mock.calls[3][1]; - assert.expect(createSecondNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes"); - assert.expect(createSecondNotificationType.method).to.be.equal("post"); - assert.expect(createSecondNotificationType.data).to.be.deep.eql(toNTypeWithPrefixedKey(toNTypeWithDefaultVersion(notificationTypeWithoutVersion))); - - assert.expect(httpClient.executeHttpRequest.mock.calls[4]).to.be.equal(undefined); - }); - }); - - test("Given 2 New Notification Types and 2 Existing Notification Types (+ 1 from another app) and they are the same | When process is called | Than nothing is done", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - notificationTypes.processNotificationTypes([copy(notificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - assert.expect(httpClient.executeHttpRequest.mock.calls[1]).to.be.equal(undefined); - }); - }); - - test("Given 1 New Notification Types and 2 Existing Notification Types (+ 1 from another app) and they are the same | When process is called | Than One Notification Type is deleted", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - notificationTypes.processNotificationTypes([copy(notificationTypeWithAllProperties)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const deleteSecondNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(deleteSecondNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes(guid'719d8f6a-1e07-4981-b2be-07197cec7492')"); - assert.expect(deleteSecondNotificationType.method).to.be.equal("delete"); - - assert.expect(httpClient.executeHttpRequest.mock.calls[2]).to.be.equal(undefined); - }); - }); - - test("Given 2 New Notification Types and 2 Existing Notification Types (+ 1 from another app) and they are changed | When process is called | Than notification types are updated", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - const updatedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - updatedNotificationTypeWithAllProperties.Templates[0].Description = "New Description"; - const updatedNotificationTypeWithoutVersion = copy(notificationTypeWithoutVersion); - updatedNotificationTypeWithoutVersion.Templates[0].Description = "New Description"; - - notificationTypes.processNotificationTypes([copy(updatedNotificationTypeWithAllProperties), copy(updatedNotificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const updateFirstNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(updateFirstNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); - assert.expect(updateFirstNotificationType.method).to.be.equal("patch"); - assert.expect(updateFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(updatedNotificationTypeWithAllProperties)); - - const updateSecondNotificationType = httpClient.executeHttpRequest.mock.calls[2][1]; - assert.expect(updateSecondNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes(guid'719d8f6a-1e07-4981-b2be-07197cec7492')"); - assert.expect(updateSecondNotificationType.method).to.be.equal("patch"); - assert.expect(updateSecondNotificationType.data).to.be.deep.eql(toNTypeWithPrefixedKey(toNTypeWithDefaultVersion(updatedNotificationTypeWithoutVersion))); - - assert.expect(httpClient.executeHttpRequest.mock.calls[3]).to.be.equal(undefined); - }); - }); - - test("Given NType with additional Template | When process is called | Than notification type is updated", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - const updatedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - updatedNotificationTypeWithAllProperties.Templates[1] = updatedNotificationTypeWithAllProperties.Templates[0]; - updatedNotificationTypeWithAllProperties.Templates[1].Language = "DE"; - - notificationTypes.processNotificationTypes([copy(updatedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const updateFirstNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(updateFirstNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); - assert.expect(updateFirstNotificationType.method).to.be.equal("patch"); - assert.expect(updateFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(updatedNotificationTypeWithAllProperties)); - - assert.expect(httpClient.executeHttpRequest.mock.calls[2]).to.be.equal(undefined); - }); - }); - - test("Given NType with additional Actions | When process is called | Than notification type is updated", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - const updatedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - updatedNotificationTypeWithAllProperties.Actions[1] = updatedNotificationTypeWithAllProperties.Actions[0]; - updatedNotificationTypeWithAllProperties.Actions[1].Language = "DE"; - - notificationTypes.processNotificationTypes([copy(updatedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const updateFirstNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(updateFirstNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); - assert.expect(updateFirstNotificationType.method).to.be.equal("patch"); - assert.expect(updateFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(updatedNotificationTypeWithAllProperties)); - - assert.expect(httpClient.executeHttpRequest.mock.calls[2]).to.be.equal(undefined); - }); - }); - - test("Given NType with additional DeliveryChannels | When process is called | Than notification type is updated", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - const updatedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - updatedNotificationTypeWithAllProperties.DeliveryChannels[1] = updatedNotificationTypeWithAllProperties.DeliveryChannels[0]; - updatedNotificationTypeWithAllProperties.DeliveryChannels[1].Type = "MOBILE"; - - notificationTypes.processNotificationTypes([copy(updatedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const updateFirstNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(updateFirstNotificationType.url).to.be.equal("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); - assert.expect(updateFirstNotificationType.method).to.be.equal("patch"); - assert.expect(updateFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(updatedNotificationTypeWithAllProperties)); - - assert.expect(httpClient.executeHttpRequest.mock.calls[2]).to.be.equal(undefined); - }); - }); - - test("Given arrays with results | When process is called | Then nothing is done", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - const changedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - changedNotificationTypeWithAllProperties.Templates = { results: notificationTypeWithAllProperties.Templates }; - changedNotificationTypeWithAllProperties.Actions = { results: notificationTypeWithAllProperties.Actions }; - changedNotificationTypeWithAllProperties.DeliveryChannels = { results: notificationTypeWithAllProperties.DeliveryChannels }; - - notificationTypes.processNotificationTypes([copy(changedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - assert.expect(httpClient.executeHttpRequest.mock.calls[1]).to.be.equal(undefined); - }); - }); - - test("Given arrays with results | When process is called | Then nothing is done", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - const changedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - changedNotificationTypeWithAllProperties.IsGroupable = undefined; - notificationTypes.processNotificationTypes([copy(changedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - assert.expect(httpClient.executeHttpRequest.mock.calls[1]).to.be.equal(undefined); - }); - }); - - test("Given language in lower case | When process is called | Then nothing is done", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - const changedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - changedNotificationTypeWithAllProperties.Templates[0].Language = notificationTypeWithAllProperties.Templates[0].Language.toLowerCase(); - changedNotificationTypeWithAllProperties.Actions[0].Language = notificationTypeWithAllProperties.Actions[0].Language.toLowerCase(); - - notificationTypes.processNotificationTypes([copy(changedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - assert.expect(httpClient.executeHttpRequest.mock.calls[1]).to.be.equal(undefined); - }); - }); - - test("Given template language in lower case | When process is called | Then nothing is done", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - const changedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - changedNotificationTypeWithAllProperties.Templates[0].TemplateLanguage = notificationTypeWithAllProperties.Templates[0].TemplateLanguage.toLowerCase(); - - notificationTypes.processNotificationTypes([copy(changedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - assert.expect(httpClient.executeHttpRequest.mock.calls[1]).to.be.equal(undefined); - }); - }); - - test("Given empty Templates, Actions and Delivery Channels in both new and old | When process is called | Then nothing is done", () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingWithUndefinedTemplatesActionsAndDeliveryChannelsResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - notificationTypes.processNotificationTypes([copy(notificationTypeWithNullTemplatesActionsAndDeliveryChannels)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - assert.expect(httpClient.executeHttpRequest.mock.calls[1]).to.be.equal(undefined); - }); - }); - - test("Given that NType is different | When process is called | Then NType is updated", async () => { - utils.getNotificationDestination.mockReturnValue(undefined); - httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); - connectivity.buildHeadersForDestination.mockReturnValue({}); - utils.getNotificationTypesKeyWithPrefix.mockImplementation((str) => testPrefix + "/" + str); - utils.getPrefix.mockReturnValue(testPrefix); - - var ntypeProperties = Object.entries(notificationTypeWithAllProperties); - for (var ntypeProperty of ntypeProperties) { - if (ntypeProperty[0] == "NotificationTypeKey" || ntypeProperty[0] == "NotificationTypeVersion") { - continue; - } - const changedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - - console.log(ntypeProperty); - if (typeof ntypeProperty[1] === "string") { - changedNotificationTypeWithAllProperties[ntypeProperty[0]] = ntypeProperty[1] + " UPDATED"; - } else if (typeof ntypeProperty[1] === "boolean") { - changedNotificationTypeWithAllProperties[ntypeProperty[0]] = !ntypeProperty[1]; - } else if (typeof ntypeProperty[1] === "number") { - changedNotificationTypeWithAllProperties[ntypeProperty[0]] = ntypeProperty[1] + 1; - } else { - continue; - } - await notificationTypes.processNotificationTypes([copy(changedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const updateFirstNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(updateFirstNotificationType.url).to.equal("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); - assert.expect(updateFirstNotificationType.method).to.equal("patch"); - assert.expect(updateFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(changedNotificationTypeWithAllProperties)); - - assert.expect(httpClient.executeHttpRequest.mock.calls[2]).to.be.equal(undefined); - }); - jest.clearAllMocks(); - } - - var templateProperties = Object.entries(notificationTypeWithAllProperties.Templates[0]); - for (var templateProperty of templateProperties) { - const changedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - - if (typeof templateProperty[1] === "string") { - changedNotificationTypeWithAllProperties.Templates[0][templateProperty[0]] = templateProperty[1] + " UPDATED"; - } else if (typeof templateProperty[1] === "boolean") { - changedNotificationTypeWithAllProperties.Templates[0][templateProperty[0]] = !templateProperty[1]; - } else if (typeof templateProperty[1] === "number") { - changedNotificationTypeWithAllProperties.Templates[0][templateProperty[0]] = templateProperty[1] + 1; - } else { - continue; - } - await notificationTypes.processNotificationTypes([copy(changedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const updateFirstNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(updateFirstNotificationType.url).to.equal("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); - assert.expect(updateFirstNotificationType.method).to.equal("patch"); - assert.expect(updateFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(changedNotificationTypeWithAllProperties)); - - assert.expect(httpClient.executeHttpRequest.mock.calls[2]).to.be.equal(undefined); - }); - jest.clearAllMocks(); - } - - var actionProperties = Object.entries(notificationTypeWithAllProperties.Actions[0]); - for (var actionProperty of actionProperties) { - const changedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - - if (typeof actionProperty[1] === "string") { - changedNotificationTypeWithAllProperties.Actions[0][actionProperty[0]] = actionProperty[1] + " UPDATED"; - } else if (typeof actionProperty[1] === "boolean") { - changedNotificationTypeWithAllProperties.Actions[0][actionProperty[0]] = !actionProperty[1]; - } else if (typeof actionProperty[1] === "number") { - changedNotificationTypeWithAllProperties.Actions[0][actionProperty[0]] = actionProperty[1] + 1; - } else { - continue; - } - await notificationTypes.processNotificationTypes([copy(changedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const updateFirstNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(updateFirstNotificationType.url).to.equal("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); - assert.expect(updateFirstNotificationType.method).to.equal("patch"); - assert.expect(updateFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(changedNotificationTypeWithAllProperties)); - - assert.expect(httpClient.executeHttpRequest.mock.calls[2]).to.be.equal(undefined); - }); - jest.clearAllMocks(); - } - - var deliveryChannelProperties = Object.entries(notificationTypeWithAllProperties.DeliveryChannels[0]); - for (var deliveryChannelProperty of deliveryChannelProperties) { - const changedNotificationTypeWithAllProperties = copy(notificationTypeWithAllProperties); - - if (typeof deliveryChannelProperty[1] === "string") { - changedNotificationTypeWithAllProperties.DeliveryChannels[0][deliveryChannelProperty[0]] = deliveryChannelProperty[1] + " UPDATED"; - } else if (typeof deliveryChannelProperty[1] === "boolean") { - changedNotificationTypeWithAllProperties.DeliveryChannels[0][deliveryChannelProperty[0]] = !deliveryChannelProperty[1]; - } else if (typeof deliveryChannelProperty[1] === "number") { - changedNotificationTypeWithAllProperties.DeliveryChannels[0][deliveryChannelProperty[0]] = deliveryChannelProperty[1] + 1; - } else { - continue; - } - await notificationTypes.processNotificationTypes([copy(changedNotificationTypeWithAllProperties), copy(notificationTypeWithoutVersion)]).then(() => { - const getAllNotificationTypesRequest = httpClient.executeHttpRequest.mock.calls[0][1]; - assert.expect(getAllNotificationTypesRequest.url).to.equal("v2/NotificationType.svc/NotificationTypes?$format=json&$expand=Templates,Actions,DeliveryChannels"); - assert.expect(getAllNotificationTypesRequest.method).to.equal("get"); - - const updateFirstNotificationType = httpClient.executeHttpRequest.mock.calls[1][1]; - assert.expect(updateFirstNotificationType.url).to.equal("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); - assert.expect(updateFirstNotificationType.method).to.equal("patch"); - assert.expect(updateFirstNotificationType.data).to.be.deep.equal(toNTypeWithPrefixedKey(changedNotificationTypeWithAllProperties)); - - assert.expect(httpClient.executeHttpRequest.mock.calls[2]).to.be.equal(undefined); - }); - jest.clearAllMocks(); - } - }); -}); - -function toNTypeWithPrefixedKey(ntype) { - var prefixedNtype = copy(ntype); - prefixedNtype.NotificationTypeKey = testPrefix + "/" + prefixedNtype.NotificationTypeKey; - return prefixedNtype; -} - -function toNTypeWithDefaultVersion(ntype) { - var ntypeWithVersion = copy(ntype); - ntypeWithVersion.NotificationTypeVersion = "1"; - return ntypeWithVersion; -} - -function copy(obj) { - return JSON.parse(JSON.stringify(obj)); -} - -const defaultNotificationType = { - NotificationTypeKey: "Default", - NotificationTypeVersion: "1", - Templates: [ - { - Language: "en", - Description: "Other Notifications", - TemplatePublic: "{{title}}", - TemplateSensitive: "{{title}}", - TemplateGrouped: "Other Notifications", - TemplateLanguage: "mustache", - Subtitle: "{{description}}" - } - ] -}; - -const notificationTypeWithAllProperties = { - NotificationTypeKey: "notificationTypeWithAllProperties", - NotificationTypeVersion: "1", - IsGroupable: true, - Templates: [ - { - Language: "EN", - TemplatePublic: "TemplatePublic", - TemplateSensitive: "TemplateSensitive", - TemplateGrouped: "TemplateGrouped", - Description: "Description", - TemplateLanguage: "MUSTACHE", - Subtitle: "Subtitle", - EmailSubject: "EmailSubject", - EmailText: "EmailText", - EmailHtml: "EmailHtml" - } - ], - Actions: [ - { - ActionId: "Accept", - Language: "EN", - ActionText: "Accept", - GroupActionText: "Accept All", - Nature: "POSITIVE" - } - ], - DeliveryChannels: [ - { - Type: "WEB", - Enabled: true, - DefaultPreference: false, - EditablePreference: true - } - ] -}; - -const notificationTypeWithoutVersion = { - NotificationTypeKey: "notificationTypeWithoutVersion", - IsGroupable: true, - Templates: [ - { - Language: "EN", - TemplatePublic: "TemplatePublic", - TemplateSensitive: "TemplateSensitive", - TemplateGrouped: "TemplateGrouped", - Description: "Description", - TemplateLanguage: "MUSTACHE", - Subtitle: "Subtitle", - EmailSubject: "EmailSubject", - EmailText: "EmailText", - EmailHtml: "EmailHtml" - } - ], - Actions: [ - { - ActionId: "Accept", - Language: "EN", - ActionText: "Accept", - GroupActionText: "Accept All", - Nature: "POSITIVE" - } - ], - DeliveryChannels: [ - { - Type: "WEB", - Enabled: true, - DefaultPreference: false, - EditablePreference: true - } - ] -}; - -const notificationTypeWithNullTemplatesActionsAndDeliveryChannels = { - NotificationTypeKey: "notificationTypeWithAllProperties", - NotificationTypeVersion: "1", - IsGroupable: true, - Templates: null, - Actions: null, - DeliveryChannels: null -}; - -const testPrefix = "test-prefix"; - -const emptyResponseBody = { data: { d: { results: [] } } }; - -const allExistingResponseBody = { - data: { - d: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'a6771115-42f4-4ac3-9c85-49a819927b9c')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'a6771115-42f4-4ac3-9c85-49a819927b9c')", - type: "com.SAP.OData.V2.NotificationTypeService.NotificationType" - }, - NotificationTypeId: "a6771115-42f4-4ac3-9c85-49a819927b9c", - NotificationTypeKey: "Default", - NotificationTypeVersion: "1", - IsGroupable: true, - Templates: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'a6771115-42f4-4ac3-9c85-49a819927b9c',Language='EN')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'a6771115-42f4-4ac3-9c85-49a819927b9c',Language='EN')", - type: "com.SAP.OData.V2.NotificationTypeService.Template" - }, - NotificationTypeId: "a6771115-42f4-4ac3-9c85-49a819927b9c", - Language: "EN", - TemplatePublic: "{{title}}", - TemplateSensitive: "{{title}}", - TemplateGrouped: "Other Notifications", - Description: "Other Notifications", - TemplateLanguage: "MUSTACHE", - Subtitle: "{{description}}", - EmailSubject: null, - EmailText: null, - EmailHtml: null - } - ] - }, - Actions: { - results: [] - }, - DeliveryChannels: { - results: [] - } - }, - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')", - type: "com.SAP.OData.V2.NotificationTypeService.NotificationType" - }, - NotificationTypeId: "26f1fad0-de4c-4869-9b4e-62f445c8a7a8", - NotificationTypeKey: "test-prefix/notificationTypeWithAllProperties", - NotificationTypeVersion: "1", - IsGroupable: true, - Templates: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8',Language='EN')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8',Language='EN')", - type: "com.SAP.OData.V2.NotificationTypeService.Template" - }, - NotificationTypeId: "26f1fad0-de4c-4869-9b4e-62f445c8a7a8", - Language: "EN", - TemplatePublic: "TemplatePublic", - TemplateSensitive: "TemplateSensitive", - TemplateGrouped: "TemplateGrouped", - Description: "Description", - TemplateLanguage: "MUSTACHE", - Subtitle: "Subtitle", - EmailSubject: "EmailSubject", - EmailText: "EmailText", - EmailHtml: "EmailHtml" - } - ] - }, - Actions: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Actions(ActionId='Accept',Language='EN',NotificationTypeId=guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Actions(ActionId='Accept',Language='EN',NotificationTypeId=guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')", - type: "com.SAP.OData.V2.NotificationTypeService.Action" - }, - NotificationTypeId: "26f1fad0-de4c-4869-9b4e-62f445c8a7a8", - ActionId: "Accept", - ActionText: "Accept", - GroupActionText: "Accept All", - Language: "EN", - Nature: "POSITIVE" - } - ] - }, - DeliveryChannels: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/DeliveryChannels('WEB')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/DeliveryChannels('WEB')", - type: "com.SAP.OData.V2.NotificationTypeService.DeliveryChannel" - }, - Type: "WEB", - Enabled: true, - DefaultPreference: false, - EditablePreference: true - } - ] - } - }, - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'5b641f19-7c05-404b-b9a3-f6326f8b23ad')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'5b641f19-7c05-404b-b9a3-f6326f8b23ad')", - type: "com.SAP.OData.V2.NotificationTypeService.NotificationType" - }, - NotificationTypeId: "5b641f19-7c05-404b-b9a3-f6326f8b23ad", - NotificationTypeKey: "test-prefix-2/notificationTypeWithAllProperties", - NotificationTypeVersion: "1", - IsGroupable: true, - Templates: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'5b641f19-7c05-404b-b9a3-f6326f8b23ad',Language='EN')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'5b641f19-7c05-404b-b9a3-f6326f8b23ad',Language='EN')", - type: "com.SAP.OData.V2.NotificationTypeService.Template" - }, - NotificationTypeId: "5b641f19-7c05-404b-b9a3-f6326f8b23ad", - Language: "EN", - TemplatePublic: "TemplatePublic", - TemplateSensitive: "TemplateSensitive", - TemplateGrouped: "TemplateGrouped", - Description: "Description", - TemplateLanguage: "MUSTACHE", - Subtitle: "Subtitle", - EmailSubject: "EmailSubject", - EmailText: "EmailText", - EmailHtml: "EmailHtml" - } - ] - }, - Actions: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Actions(ActionId='Accept',Language='EN',NotificationTypeId=guid'5b641f19-7c05-404b-b9a3-f6326f8b23ad')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Actions(ActionId='Accept',Language='EN',NotificationTypeId=guid'5b641f19-7c05-404b-b9a3-f6326f8b23ad')", - type: "com.SAP.OData.V2.NotificationTypeService.Action" - }, - NotificationTypeId: "5b641f19-7c05-404b-b9a3-f6326f8b23ad", - ActionId: "Accept", - ActionText: "Accept", - GroupActionText: "Accept All", - Language: "EN", - Nature: "POSITIVE" - } - ] - }, - DeliveryChannels: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/DeliveryChannels('WEB')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/DeliveryChannels('WEB')", - type: "com.SAP.OData.V2.NotificationTypeService.DeliveryChannel" - }, - Type: "WEB", - Enabled: true, - DefaultPreference: false, - EditablePreference: true - } - ] - } - }, - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'719d8f6a-1e07-4981-b2be-07197cec7492')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'719d8f6a-1e07-4981-b2be-07197cec7492')", - type: "com.SAP.OData.V2.NotificationTypeService.NotificationType" - }, - NotificationTypeId: "719d8f6a-1e07-4981-b2be-07197cec7492", - NotificationTypeKey: "test-prefix/notificationTypeWithoutVersion", - NotificationTypeVersion: "1", - IsGroupable: true, - Templates: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'719d8f6a-1e07-4981-b2be-07197cec7492',Language='EN')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'719d8f6a-1e07-4981-b2be-07197cec7492',Language='EN')", - type: "com.SAP.OData.V2.NotificationTypeService.Template" - }, - NotificationTypeId: "719d8f6a-1e07-4981-b2be-07197cec7492", - Language: "EN", - TemplatePublic: "TemplatePublic", - TemplateSensitive: "TemplateSensitive", - TemplateGrouped: "TemplateGrouped", - Description: "Description", - TemplateLanguage: "MUSTACHE", - Subtitle: "Subtitle", - EmailSubject: "EmailSubject", - EmailText: "EmailText", - EmailHtml: "EmailHtml" - } - ] - }, - Actions: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Actions(ActionId='Accept',Language='EN',NotificationTypeId=guid'719d8f6a-1e07-4981-b2be-07197cec7492')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Actions(ActionId='Accept',Language='EN',NotificationTypeId=guid'719d8f6a-1e07-4981-b2be-07197cec7492')", - type: "com.SAP.OData.V2.NotificationTypeService.Action" - }, - NotificationTypeId: "719d8f6a-1e07-4981-b2be-07197cec7492", - ActionId: "Accept", - ActionText: "Accept", - GroupActionText: "Accept All", - Language: "EN", - Nature: "POSITIVE" - } - ] - }, - DeliveryChannels: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/DeliveryChannels('WEB')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/DeliveryChannels('WEB')", - type: "com.SAP.OData.V2.NotificationTypeService.DeliveryChannel" - }, - Type: "WEB", - Enabled: true, - DefaultPreference: false, - EditablePreference: true - } - ] - } - } - ] - } - } -}; - -const allExistingWithUndefinedTemplatesActionsAndDeliveryChannelsResponseBody = { - data: { - d: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'a6771115-42f4-4ac3-9c85-49a819927b9c')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'a6771115-42f4-4ac3-9c85-49a819927b9c')", - type: "com.SAP.OData.V2.NotificationTypeService.NotificationType" - }, - NotificationTypeId: "a6771115-42f4-4ac3-9c85-49a819927b9c", - NotificationTypeKey: "Default", - NotificationTypeVersion: "1", - IsGroupable: true, - Templates: { - results: [ - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'a6771115-42f4-4ac3-9c85-49a819927b9c',Language='EN')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/Templates(NotificationTypeId=guid'a6771115-42f4-4ac3-9c85-49a819927b9c',Language='EN')", - type: "com.SAP.OData.V2.NotificationTypeService.Template" - }, - NotificationTypeId: "a6771115-42f4-4ac3-9c85-49a819927b9c", - Language: "EN", - TemplatePublic: "{{title}}", - TemplateSensitive: "{{title}}", - TemplateGrouped: "Other Notifications", - Description: "Other Notifications", - TemplateLanguage: "MUSTACHE", - Subtitle: "{{description}}", - EmailSubject: null, - EmailText: null, - EmailHtml: null - } - ] - }, - Actions: { - results: null - }, - DeliveryChannels: {} - }, - { - __metadata: { - id: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')", - uri: "https://notifications.cfapps.eu12.hana.ondemand.com:443/v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')", - type: "com.SAP.OData.V2.NotificationTypeService.NotificationType" - }, - NotificationTypeId: "26f1fad0-de4c-4869-9b4e-62f445c8a7a8", - NotificationTypeKey: "test-prefix/notificationTypeWithAllProperties", - NotificationTypeVersion: "1", - IsGroupable: true - } - ] - } - } -}; diff --git a/tests/lib/notifications.test.js b/tests/lib/notifications.test.js deleted file mode 100644 index 55d7c9f..0000000 --- a/tests/lib/notifications.test.js +++ /dev/null @@ -1,150 +0,0 @@ -const { getNotificationDestination } = require("./../../lib/utils"); -const { buildHeadersForDestination } = require("@sap-cloud-sdk/connectivity"); -const NotifyToRest = require("./../../srv/notifyToRest"); -const { executeHttpRequest } = require("@sap-cloud-sdk/http-client"); - -jest.mock("./../../lib/utils"); -jest.mock("@sap-cloud-sdk/connectivity"); -jest.mock("@sap-cloud-sdk/http-client") - -const expectedCustomNotification = { - NotificationTypeKey: "Custom", - NotificationTypeVersion: "1", - Priority: "HIGH", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Text Title", - Type: "String" - }, - { - Key: "description", - IsSensitive: false, - Language: "en", - Value: "Some Text Description", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ] -}; - -describe("Test post notification", () => { - - test("When passed whole notification object to postNotification", async () => { - const alert = new NotifyToRest - const infoSpy = jest.spyOn(global.console, 'info'); - getNotificationDestination.mockReturnValue(undefined); - buildHeadersForDestination.mockReturnValue(undefined); - executeHttpRequest.mockReturnValue(expectedCustomNotification); - - // call post notification - await alert.postNotification(expectedCustomNotification) - - // check if console.info was called - expect(infoSpy).toHaveBeenCalled(); - expect(infoSpy).toHaveBeenCalledWith("[notifications] -", "Sending notification of key: Custom and version: 1"); - - // check if execute http request was called - expect(executeHttpRequest).toHaveBeenCalled(); - infoSpy.mockClear(); - }) - - test("When execute http request throws error with status code 500", async () => { - const alert = new NotifyToRest - const error = new Error(); - error.response = { - message: "mocked error", - status: 500 - }; - - const infoSpy = jest.spyOn(global.console, 'info'); - getNotificationDestination.mockReturnValue(undefined); - buildHeadersForDestination.mockReturnValue(undefined); - executeHttpRequest.mockImplementation(() => { - throw error; - }); - - // call post notification - try { - await alert.postNotification(expectedCustomNotification); - } catch (err) { - expect(err.unrecoverable).toBeFalsy(); - } - - // check if console.info was called - expect(infoSpy).toHaveBeenCalled(); - expect(infoSpy).toHaveBeenCalledWith("[notifications] -", "Sending notification of key: Custom and version: 1"); - - // check if execute http request was called - expect(executeHttpRequest).toHaveBeenCalled(); - infoSpy.mockClear(); - }) - - test("When execute http request throws error with status code 404", async () => { - const alert = new NotifyToRest - const error = new Error(); - error.response = { - message: "mocked error", - status: 404 - }; - - const infoSpy = jest.spyOn(global.console, 'info'); - getNotificationDestination.mockReturnValue(undefined); - buildHeadersForDestination.mockReturnValue(undefined); - executeHttpRequest.mockImplementation(() => { - throw error; - }); - - // call post notification - try { - await alert.postNotification(expectedCustomNotification); - } catch (err) { - expect(err.unrecoverable).toEqual(true); - } - - // check if console.info was called - expect(infoSpy).toHaveBeenCalled(); - expect(infoSpy).toHaveBeenCalledWith("[notifications] -", "Sending notification of key: Custom and version: 1"); - - // check if execute http request was called - expect(executeHttpRequest).toHaveBeenCalled(); - infoSpy.mockClear(); - }) - - test("When execute http request throws error with status code 429", async () => { - const alert = new NotifyToRest - const error = new Error(); - error.response = { - message: "mocked error", - status: 429 - }; - - const infoSpy = jest.spyOn(global.console, 'info'); - getNotificationDestination.mockReturnValue(undefined); - buildHeadersForDestination.mockReturnValue(undefined); - executeHttpRequest.mockImplementation(() => { - throw error; - }); - - // call post notification - try { - await alert.postNotification(expectedCustomNotification); - } catch (err) { - expect(err.unrecoverable).toBeFalsy(); - } - - // check if console.info was called - expect(infoSpy).toHaveBeenCalled(); - expect(infoSpy).toHaveBeenCalledWith("[notifications] -", "Sending notification of key: Custom and version: 1"); - - // check if execute http request was called - expect(executeHttpRequest).toHaveBeenCalled(); - infoSpy.mockClear(); - }) -}) diff --git a/tests/lib/utils.test.js b/tests/lib/utils.test.js deleted file mode 100644 index 883a218..0000000 --- a/tests/lib/utils.test.js +++ /dev/null @@ -1,571 +0,0 @@ -const { buildNotification, validateNotificationTypes, readFile, getNotificationDestination } = require("../../lib/utils"); -const { existsSync, readFileSync } = require("fs"); -const { getDestination } = require("@sap-cloud-sdk/connectivity"); - -jest.mock("fs"); -jest.mock("@sap-cloud-sdk/connectivity"); - -const expectedDefaultNotificationWithoutDescription = { - NotificationTypeKey: "Default", - NotificationTypeVersion: "1", - Priority: "NEUTRAL", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - }, - { - Key: "description", - IsSensitive: false, - Language: "en", - Value: "", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ] -}; - -const expectedDefaultNotificationWithDescription = { - NotificationTypeKey: "Default", - NotificationTypeVersion: "1", - Priority: "NEUTRAL", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - }, - { - Key: "description", - IsSensitive: false, - Language: "en", - Value: "Some Test Description", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ] -}; - -describe("Test utils", () => { - test("When recipients, priority, title are passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - title: "Some Test Title", - priority: "NEUTRAL" - }) - ).toMatchObject(expectedDefaultNotificationWithoutDescription); - }); - - test("When recipients, priority, title, description are passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - title: "Some Test Title", - priority: "NEUTRAL", - description: "Some Test Description" - }) - ).toMatchObject(expectedDefaultNotificationWithDescription); - }); - - test("When recipients, title are passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - title: "Some Test Title" - }) - ).toMatchObject(expectedDefaultNotificationWithoutDescription); - }); - - test("When recipients, title, description are passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - title: "Some Test Title", - description: "Some Test Description" - }) - ).toMatchObject(expectedDefaultNotificationWithDescription); - }); - - test("When recipients, type, properties are passed to buildNotification", () => { - const expectedNotification = { - NotificationTypeKey: "notifications/TestNotificationType", - NotificationTypeVersion: "1", - Priority: "NEUTRAL", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ] - }; - - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - type: "TestNotificationType", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ] - }) - ).toMatchObject(expectedNotification); - }); - - test("When recipients, type, properties, navigation are passed to buildNotification", () => { - const expectedNotification = { - NotificationTypeKey: "notifications/TestNotificationType", - NotificationTypeVersion: "1", - NavigationTargetAction: "TestTargetAction", - NavigationTargetObject: "TestTargetObject", - Priority: "NEUTRAL", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ] - }; - - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - type: "TestNotificationType", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - NavigationTargetAction: "TestTargetAction", - NavigationTargetObject: "TestTargetObject", - }) - ).toMatchObject(expectedNotification); - }); - - test("When recipients, type, properties, navigation, priority are passed to buildNotification", () => { - const expectedNotification = { - NotificationTypeKey: "notifications/TestNotificationType", - NotificationTypeVersion: "1", - NavigationTargetAction: "TestTargetAction", - NavigationTargetObject: "TestTargetObject", - Priority: "HIGH", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ] - }; - - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - type: "TestNotificationType", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - NavigationTargetAction: "TestTargetAction", - NavigationTargetObject: "TestTargetObject", - priority: "HIGH" - }) - ).toMatchObject(expectedNotification); - }); - - test("When recipients, type, properties, navigation, priority, payload are passed to buildNotification", () => { - const expectedNotification = { - OriginId: "01234567-89ab-cdef-0123-456789abcdef", - NotificationTypeId: "01234567-89ab-cdef-0123-456789abcdef", - NotificationTypeKey: "notifications/TestNotificationType", - NotificationTypeVersion: "1", - NavigationTargetAction: "TestTargetAction", - NavigationTargetObject: "TestTargetObject", - Priority: "HIGH", - ProviderId: "SAMPLEPROVIDER", - ActorId: "BACKENDACTORID", - ActorDisplayText: "ActorName", - ActorImageURL: "https://some-url", - NotificationTypeTimestamp: "2022-03-15T09:58:42.807Z", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ], - TargetParameters: [ - { - Key: "string", - Value: "string" - } - ] - }; - - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - type: "TestNotificationType", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - NavigationTargetAction: "TestTargetAction", - NavigationTargetObject: "TestTargetObject", - priority: "HIGH", - OriginId: "01234567-89ab-cdef-0123-456789abcdef", - NotificationTypeId: "01234567-89ab-cdef-0123-456789abcdef", - ProviderId: "SAMPLEPROVIDER", - ActorId: "BACKENDACTORID", - ActorDisplayText: "ActorName", - ActorImageURL: "https://some-url", - NotificationTypeTimestamp: "2022-03-15T09:58:42.807Z", - TargetParameters: [ - { - Key: "string", - Value: "string" - } - ] - }) - ).toMatchObject(expectedNotification); - }); - - test("When recipients, type, properties, navigation, priority, but with not all the payload are passed to buildNotification", () => { - const expectedNotification = { - NotificationTypeId: "01234567-89ab-cdef-0123-456789abcdef", - NotificationTypeKey: "notifications/TestNotificationType", - NotificationTypeVersion: "1", - NavigationTargetAction: "TestTargetAction", - NavigationTargetObject: "TestTargetObject", - Priority: "HIGH", - ProviderId: "SAMPLEPROVIDER", - ActorId: "BACKENDACTORID", - ActorDisplayText: "ActorName", - ActorImageURL: "https://some-url", - NotificationTypeTimestamp: "2022-03-15T09:58:42.807Z", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ], - TargetParameters: [ - { - Key: "string", - Value: "string" - } - ] - }; - - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - type: "TestNotificationType", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - } - ], - NavigationTargetAction: "TestTargetAction", - NavigationTargetObject: "TestTargetObject", - priority: "HIGH", - NotificationTypeId: "01234567-89ab-cdef-0123-456789abcdef", - ProviderId: "SAMPLEPROVIDER", - ActorId: "BACKENDACTORID", - ActorDisplayText: "ActorName", - ActorImageURL: "https://some-url", - NotificationTypeTimestamp: "2022-03-15T09:58:42.807Z", - TargetParameters: [ - { - Key: "string", - Value: "string" - } - ] - }) - ).toMatchObject(expectedNotification); - }); - - test("When whole notification object is passed to buildNotification", () => { - const expectedNotification = { - NotificationTypeKey: "notifications/TestNotificationType", - NotificationTypeVersion: "1", - Priority: "NEUTRAL", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - }, - { - Key: "description", - IsSensitive: false, - Language: "en", - Value: "Some Test Description", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ] - }; - - expect( - buildNotification({ - NotificationTypeKey: "TestNotificationType", - NotificationTypeVersion: "1", - Priority: "NEUTRAL", - Properties: [ - { - Key: "title", - IsSensitive: false, - Language: "en", - Value: "Some Test Title", - Type: "String" - }, - { - Key: "description", - IsSensitive: false, - Language: "en", - Value: "Some Test Description", - Type: "String" - } - ], - Recipients: [ - { - RecipientId: "test.mail@mail.com" - } - ] - }) - ).toMatchObject(expectedNotification); - }); - - test("When empty object is passed to buildNotification", () => { - expect(buildNotification({})).toBeFalsy(); - }); - - test("When not all mandatory parameters for default notification are passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - priority: "NEUTRAL" - }) - ).toBeFalsy(); - }); - - test("When empty recipients array for default notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: [], - title: "Some Test Title", - priority: "NEUTRAL" - }) - ).toBeFalsy(); - }); - - test("When string is passed as recipients for default notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: "invalid", - title: "Some Test Title", - priority: "NEUTRAL" - }) - ).toBeFalsy(); - }); - - test("When invalid priority for default notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - title: "Some Test Title", - priority: "INVALID" - }) - ).toBeFalsy(); - }); - - test("When invalid description for default notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - title: "Some Test Title", - priority: "NEUTRAL", - description: { invalid: "invalid" } - }) - ).toBeFalsy(); - }); - - test("When invalid title for default notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - title: { invalid: "invalid" }, - priority: "NEUTRAL" - }) - ).toBeFalsy(); - }); - - test("When not all mandatory parameters for custom notification are passed to buildNotification", () => { - expect( - buildNotification({ - type: "TestNotificationType" - }) - ).toBeFalsy(); - }); - - test("When empty array of recipients for custom notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: [], - type: "TestNotificationType" - }) - ).toBeFalsy(); - }); - - test("When invalid recipients for custom notification are passed to buildNotification", () => { - expect( - buildNotification({ - recipients: "invalid", - type: "TestNotificationType" - }) - ).toBeFalsy(); - }); - - test("When invalid priority for custom notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - type: "TestNotificationType", - priority: "invalid" - }) - ).toBeFalsy(); - }); - - test("When invalid properties for custom notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - type: "TestNotificationType", - priority: "NEUTRAL", - properties: "invalid" - }) - ).toBeFalsy(); - }); - - test("When invalid navigation for custom notification is passed to buildNotification", () => { - expect( - buildNotification({ - recipients: ["test.mail@mail.com"], - type: "TestNotificationType", - priority: "NEUTRAL", - navigation: "invalid" - }) - ).toBeFalsy(); - }); - - test("Given invalid NTypes | When validateNotificationTypes is called | Then false is returned", () => { - expect(validateNotificationTypes([{ NotificationTypeKey: "Test" }, { blabla: "Test2" }])).toEqual(false); - }); - - test("Given valid NTypes | When validateNotificationTypes is called | Then true is returned", () => { - expect(validateNotificationTypes([])).toEqual(true); - expect(validateNotificationTypes([{ NotificationTypeKey: "Test" }, { NotificationTypeKey: "Test2" }])).toEqual(true); - }); - - test("Given that file does not exist | When readFile is called | Then empty array is returned", () => { - existsSync.mockReturnValue(false); - expect(readFile("test.json")).toMatchObject([]); - }); - - test("Given that file does exist | When readFile is called | Then correct array is returned", () => { - existsSync.mockReturnValue(true); - readFileSync.mockReturnValue('[{ "test": "test" }]'); - expect(readFile("test.json")).toMatchObject([{ test: "test" }]); - }); - - test("Given that destination does exist | When getNotificationDestination is called | Then correct destination is returned", async () => { - getDestination.mockReturnValue({ "mock-destination": "mock-destination" }); - expect(await getNotificationDestination()).toMatchObject({ "mock-destination": "mock-destination" }); - }); - - test("Given that destination does not exist | When getNotificationDestination is called | Then error is thrown", async () => { - getDestination.mockReturnValue(undefined); - await expect(() => getNotificationDestination()).rejects.toThrow("Failed to get destination: SAP_Notifications"); - }); -}); diff --git a/tests/srv/notifyToRest.test.js b/tests/srv/notifyToRest.test.js deleted file mode 100644 index e2f1348..0000000 --- a/tests/srv/notifyToRest.test.js +++ /dev/null @@ -1,61 +0,0 @@ -const { messages, buildNotification } = require("../../lib/utils"); -const NotifyToRest = require("../../srv/notifyToRest"); - -describe("notify to rest", () => { - it("when no object is passed", async () => { - const notifyToRest = new NotifyToRest(); - const warnSpy = jest.spyOn(global.console, "warn"); - notifyToRest.notify(); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.NO_OBJECT_FOR_NOTIFY); - warnSpy.mockClear(); - }); - - it("when empty object is passed", async () => { - const notifyToRest = new NotifyToRest(); - const warnSpy = jest.spyOn(global.console, "warn"); - notifyToRest.notify({}); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.EMPTY_OBJECT_FOR_NOTIFY); - warnSpy.mockClear(); - }); - - it(`when recipients or title isn't passed in default notification`, async () => { - const notifyToRest = new NotifyToRest(); - const warnSpy = jest.spyOn(global.console, "warn"); - notifyToRest.notify({ dummy: true }); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.MANDATORY_PARAMETER_NOT_PASSED_FOR_DEFAULT_NOTIFICATION); - warnSpy.mockClear(); - }); - - it(`when title isn't a string in default notification`, async () => { - const notifyToRest = new NotifyToRest(); - const warnSpy = jest.spyOn(global.console, "warn"); - notifyToRest.notify({ title: 1, recipients: ["abc@abc.com"] }); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.TITLE_IS_NOT_STRING); - warnSpy.mockClear(); - }); - - it(`when priority isn't valid in default notification`, async () => { - const notifyToRest = new NotifyToRest(); - const warnSpy = jest.spyOn(global.console, "warn"); - notifyToRest.notify({ title: "abc", recipients: ["abc@abc.com"], priority: "abc" }); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", "Invalid priority abc. Allowed priorities are LOW, NEUTRAL, MEDIUM, HIGH"); - warnSpy.mockClear(); - }); - - it(`when description isn't valid in default notification`, async () => { - const notifyToRest = new NotifyToRest(); - const warnSpy = jest.spyOn(global.console, "warn"); - notifyToRest.notify({ title: "abc", recipients: ["abc@abc.com"], priority: "low", description: true }); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.DESCRIPTION_IS_NOT_STRING); - warnSpy.mockClear(); - }); - - it(`When correct body is send | Then notification is posted`, async () => { - const body = { title: "abc", recipients: ["abc@abc.com"], priority: "low" }; - const notifyToRest = new NotifyToRest(); - let notification; notifyToRest.postNotification = n => notification = n - await notifyToRest.init(); - await notifyToRest.notify(body); - expect(notification).toMatchObject(buildNotification(body)); - }); -}); diff --git a/tests/unit/lib/content-deployment.test.js b/tests/unit/lib/content-deployment.test.js new file mode 100644 index 0000000..d50433f --- /dev/null +++ b/tests/unit/lib/content-deployment.test.js @@ -0,0 +1,53 @@ +const cds = require("@sap/cds"); +const { validateNotificationTypes, readFile } = require("../../../lib/utils"); +const { processNotificationTypes } = require("../../../lib/notificationTypes"); +const { setGlobalLogLevel } = require("@sap-cloud-sdk/util"); + +jest.mock("../../../lib/utils"); +jest.mock("../../../lib/notificationTypes"); +jest.mock("@sap-cloud-sdk/util"); + +const contentDeployment = require("../../../lib/content-deployment"); + +describe("contentDeployment", () => { + beforeEach(() => { + jest.clearAllMocks(); + setGlobalLogLevel.mockImplementation(() => undefined); + readFile.mockImplementation(() => []); + }); + + it("Set log level to error on startup", async () => { + validateNotificationTypes.mockReturnValue(false); + await contentDeployment.deployNotificationTypes(); + + expect(setGlobalLogLevel).toHaveBeenCalledWith("error"); + }); + + it("Process notification types when they are valid", async () => { + validateNotificationTypes.mockReturnValue(true); + processNotificationTypes.mockResolvedValue(); + await contentDeployment.deployNotificationTypes(); + + expect(validateNotificationTypes).toHaveBeenCalledWith([]); + expect(processNotificationTypes).toHaveBeenCalledWith([]); + }); + + it("Notification types are not processed when they are invalid", async () => { + validateNotificationTypes.mockReturnValue(false); + processNotificationTypes.mockResolvedValue(); + await contentDeployment.deployNotificationTypes(); + + expect(validateNotificationTypes).toHaveBeenCalledWith([]); + expect(processNotificationTypes).not.toHaveBeenCalled(); + }); + + it("Call readFile with empty string when notifications types path is not configured", async () => { + validateNotificationTypes.mockReturnValue(false); + const originalTypes = cds.env.requires.notifications.types; + delete cds.env.requires.notifications.types; + await contentDeployment.deployNotificationTypes(); + cds.env.requires.notifications.types = originalTypes; + + expect(readFile).toHaveBeenCalledWith(''); + }); +}); diff --git a/tests/unit/lib/notificationTypes.test.js b/tests/unit/lib/notificationTypes.test.js new file mode 100644 index 0000000..6e8c72d --- /dev/null +++ b/tests/unit/lib/notificationTypes.test.js @@ -0,0 +1,684 @@ +const utils = require("../../../lib/utils"); +const httpClient = require("@sap-cloud-sdk/http-client"); +const connectivity = require("@sap-cloud-sdk/connectivity"); +const notificationTypes = require("../../../lib/notificationTypes"); +const assert = require("chai"); + +jest.mock("../../../lib/utils"); +jest.mock("@sap-cloud-sdk/http-client"); +jest.mock("@sap-cloud-sdk/connectivity"); + +const defaultNotificationType = { + NotificationTypeKey: "Default", + NotificationTypeVersion: "1", + Templates: [ + { + Language: "en", + Description: "Other Notifications", + TemplatePublic: "{{title}}", + TemplateSensitive: "{{title}}", + TemplateGrouped: "Other Notifications", + TemplateLanguage: "mustache", + Subtitle: "{{description}}" + } + ] +}; + +const notificationTypeWithAllProperties = { + NotificationTypeKey: "notificationTypeWithAllProperties", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: [ + { + Language: "EN", + TemplatePublic: "TemplatePublic", + TemplateSensitive: "TemplateSensitive", + TemplateGrouped: "TemplateGrouped", + Description: "Description", + TemplateLanguage: "MUSTACHE", + Subtitle: "Subtitle", + EmailSubject: "EmailSubject", + EmailText: "EmailText", + EmailHtml: "EmailHtml" + } + ], + Actions: [ + { + ActionId: "Accept", + Language: "EN", + ActionText: "Accept", + GroupActionText: "Accept All", + Nature: "POSITIVE" + } + ], + DeliveryChannels: [ + { + Type: "WEB", + Enabled: true, + DefaultPreference: false, + EditablePreference: true + } + ] +}; + +const notificationTypeWithoutVersion = { + NotificationTypeKey: "notificationTypeWithoutVersion", + IsGroupable: true, + Templates: [ + { + Language: "EN", + TemplatePublic: "TemplatePublic", + TemplateSensitive: "TemplateSensitive", + TemplateGrouped: "TemplateGrouped", + Description: "Description", + TemplateLanguage: "MUSTACHE", + Subtitle: "Subtitle", + EmailSubject: "EmailSubject", + EmailText: "EmailText", + EmailHtml: "EmailHtml" + } + ], + Actions: [ + { + ActionId: "Accept", + Language: "EN", + ActionText: "Accept", + GroupActionText: "Accept All", + Nature: "POSITIVE" + } + ], + DeliveryChannels: [ + { + Type: "WEB", + Enabled: true, + DefaultPreference: false, + EditablePreference: true + } + ] +}; + +const notificationTypeWithNullTemplatesActionsAndDeliveryChannels = { + ...notificationTypeWithAllProperties, + Templates: null, + Actions: null, + DeliveryChannels: null +}; + +const testPrefix = "test-prefix"; + +const emptyResponseBody = { data: { d: { results: [] } } }; + +const allExistingResponseBody = { + data: { + d: { + results: [ + { + NotificationTypeId: "a6771115-42f4-4ac3-9c85-49a819927b9c", + NotificationTypeKey: "Default", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: { + results: [ + { + Language: "EN", + TemplatePublic: "{{title}}", + TemplateSensitive: "{{title}}", + TemplateGrouped: "Other Notifications", + Description: "Other Notifications", + TemplateLanguage: "MUSTACHE", + Subtitle: "{{description}}", + EmailSubject: null, + EmailText: null, + EmailHtml: null + } + ] + }, + Actions: { + results: [] + }, + DeliveryChannels: { + results: [] + } + }, + { + NotificationTypeId: "26f1fad0-de4c-4869-9b4e-62f445c8a7a8", + NotificationTypeKey: "test-prefix/notificationTypeWithAllProperties", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: { + results: [ + { + Language: "EN", + TemplatePublic: "TemplatePublic", + TemplateSensitive: "TemplateSensitive", + TemplateGrouped: "TemplateGrouped", + Description: "Description", + TemplateLanguage: "MUSTACHE", + Subtitle: "Subtitle", + EmailSubject: "EmailSubject", + EmailText: "EmailText", + EmailHtml: "EmailHtml" + } + ] + }, + Actions: { + results: [ + { + ActionId: "Accept", + ActionText: "Accept", + GroupActionText: "Accept All", + Language: "EN", + Nature: "POSITIVE" + } + ] + }, + DeliveryChannels: { + results: [ + { + Type: "WEB", + Enabled: true, + DefaultPreference: false, + EditablePreference: true + } + ] + } + }, + { + NotificationTypeId: "5b641f19-7c05-404b-b9a3-f6326f8b23ad", + NotificationTypeKey: "test-prefix-2/notificationTypeWithAllProperties", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: { + results: [ + { + Language: "EN", + TemplatePublic: "TemplatePublic", + TemplateSensitive: "TemplateSensitive", + TemplateGrouped: "TemplateGrouped", + Description: "Description", + TemplateLanguage: "MUSTACHE", + Subtitle: "Subtitle", + EmailSubject: "EmailSubject", + EmailText: "EmailText", + EmailHtml: "EmailHtml" + } + ] + }, + Actions: { + results: [ + { + ActionId: "Accept", + ActionText: "Accept", + GroupActionText: "Accept All", + Language: "EN", + Nature: "POSITIVE" + } + ] + }, + DeliveryChannels: { + results: [ + { + Type: "WEB", + Enabled: true, + DefaultPreference: false, + EditablePreference: true + } + ] + } + }, + { + NotificationTypeId: "719d8f6a-1e07-4981-b2be-07197cec7492", + NotificationTypeKey: "test-prefix/notificationTypeWithoutVersion", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: { + results: [ + { + Language: "EN", + TemplatePublic: "TemplatePublic", + TemplateSensitive: "TemplateSensitive", + TemplateGrouped: "TemplateGrouped", + Description: "Description", + TemplateLanguage: "MUSTACHE", + Subtitle: "Subtitle", + EmailSubject: "EmailSubject", + EmailText: "EmailText", + EmailHtml: "EmailHtml" + } + ] + }, + Actions: { + results: [ + { + ActionId: "Accept", + ActionText: "Accept", + GroupActionText: "Accept All", + Language: "EN", + Nature: "POSITIVE" + } + ] + }, + DeliveryChannels: { + results: [ + { + Type: "WEB", + Enabled: true, + DefaultPreference: false, + EditablePreference: true + } + ] + } + } + ] + } + } +}; + +const allExistingWithUndefinedTemplatesActionsAndDeliveryChannelsResponseBody = { + data: { + d: { + results: [ + { + NotificationTypeId: "a6771115-42f4-4ac3-9c85-49a819927b9c", + NotificationTypeKey: "Default", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: { + results: [ + { + NotificationTypeId: "a6771115-42f4-4ac3-9c85-49a819927b9c", + Language: "EN", + TemplatePublic: "{{title}}", + TemplateSensitive: "{{title}}", + TemplateGrouped: "Other Notifications", + Description: "Other Notifications", + TemplateLanguage: "MUSTACHE", + Subtitle: "{{description}}", + EmailSubject: null, + EmailText: null, + EmailHtml: null + } + ] + }, + Actions: { + results: null + }, + DeliveryChannels: {} + }, + { + NotificationTypeId: "26f1fad0-de4c-4869-9b4e-62f445c8a7a8", + NotificationTypeKey: "test-prefix/notificationTypeWithAllProperties", + NotificationTypeVersion: "1", + IsGroupable: true + } + ] + } + } +}; + +describe("Managing of Notification Types", () => { + beforeEach(() => { + jest.clearAllMocks(); + utils.getNotificationTypesKeyWithPrefix.mockImplementation(str => `${testPrefix}/${str}`); + }); + + describe("Create Notification Types Map", () => { + it("Seed the Default type when isLocal is true", () => { + const result = notificationTypes.createNotificationTypesMap([], true); + expect(result).toHaveProperty("Default"); + expect(result["Default"]["1"]).toMatchObject(defaultNotificationType); + }); + + it("Store multiple versions of the same type under the same key", () => { + const typeV1 = { NotificationTypeKey: "MyType", NotificationTypeVersion: "1", Templates: [] }; + const typeV2 = { NotificationTypeKey: "MyType", NotificationTypeVersion: "2", Templates: [] }; + const result = notificationTypes.createNotificationTypesMap([typeV1, typeV2]); + + expect(Object.keys(result[`${testPrefix}/MyType`])).toEqual(["1", "2"]); + }); + }); + + describe("Process Notification Types", () => { + beforeEach(() => { + utils.getNotificationDestination.mockReturnValue(undefined); + utils.getPrefix.mockReturnValue(testPrefix); + connectivity.buildHeadersForDestination.mockReturnValue({}); + }); + + describe("Creating Types", () => { + it("Create Default and all new types when none exist in Work Zone", () => { + httpClient.executeHttpRequest.mockReturnValue(emptyResponseBody); + + notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties), structuredClone(notificationTypeWithoutVersion)]).then(() => { + const [, createDefault, createFirst, createSecond, extra] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); + + expect(createDefault.method).toBe("post"); + expect(createDefault.data).toEqual(defaultNotificationType); + + expect(createFirst.method).toBe("post"); + expect(createFirst.data).toEqual(toNTypeWithPrefixedKey(notificationTypeWithAllProperties)); + + expect(createSecond.method).toBe("post"); + expect(createSecond.data).toEqual(toNTypeWithPrefixedKey({ ...notificationTypeWithoutVersion, NotificationTypeVersion: "1" })); + + expect(extra).toBeUndefined(); + }); + }); + + it("Do not create Default type when it already exists in Work Zone", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties), structuredClone(notificationTypeWithoutVersion)]).then(() => { + const postCalls = httpClient.executeHttpRequest.mock.calls.filter(c => c[1].method === "post"); + expect(postCalls).toHaveLength(0); + }); + }); + + it("Create a missing version when another version of the same type exists", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + const versionTwo = structuredClone(notificationTypeWithAllProperties); + versionTwo.NotificationTypeVersion = "2"; + + notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties), versionTwo, structuredClone(notificationTypeWithoutVersion)]).then(() => { + const createCall = httpClient.executeHttpRequest.mock.calls[1][1]; + expect(createCall.method).toBe("post"); + expect(createCall.data.NotificationTypeVersion).toBe("2"); + expect(httpClient.executeHttpRequest.mock.calls[2]).toBeUndefined(); + }); + }); + + it("Fall back gracefully when create response has no data.d", () => { + httpClient.executeHttpRequest + .mockReturnValueOnce(emptyResponseBody) + .mockReturnValue({ status: 201 }); + + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1][1].method).toBe("post"); + }); + }); + + it("Create new types correctly when existing types use OData results format", () => { + httpClient.executeHttpRequest.mockReturnValue({ + data: { + d: { + results: [ + { + NotificationTypeKey: "Default", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: { results: [] }, + Actions: { results: [] }, + DeliveryChannels: { results: [] } + } + ] + } + } + }); + + notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1][1].method).toBe("post"); + expect(httpClient.executeHttpRequest.mock.calls[2]).toBeUndefined(); + }); + }); + }); + + describe("Updating Types", () => { + it("Update all changed types", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const updatedWithAll = structuredClone(notificationTypeWithAllProperties); + updatedWithAll.Templates[0].Description = "New Description"; + const updatedWithoutVersion = structuredClone(notificationTypeWithoutVersion); + updatedWithoutVersion.Templates[0].Description = "New Description"; + + return notificationTypes.processNotificationTypes([structuredClone(updatedWithAll), structuredClone(updatedWithoutVersion)]).then(() => { + const [, updateFirst, updateSecond, extra] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); + + expect(updateFirst.url).toBe("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); + expect(updateFirst.method).toBe("patch"); + expect(updateFirst.data).toEqual(toNTypeWithPrefixedKey(updatedWithAll)); + + expect(updateSecond.url).toBe("v2/NotificationType.svc/NotificationTypes(guid'719d8f6a-1e07-4981-b2be-07197cec7492')"); + expect(updateSecond.method).toBe("patch"); + expect(updateSecond.data).toEqual(toNTypeWithPrefixedKey({ ...updatedWithoutVersion, NotificationTypeVersion: "1" })); + + expect(extra).toBeUndefined(); + }); + }); + + it("Update type when an additional Template is added", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const updated = structuredClone(notificationTypeWithAllProperties); + updated.Templates[1] = updated.Templates[0]; + updated.Templates[1].Language = "DE"; + + return notificationTypes.processNotificationTypes([structuredClone(updated), structuredClone(notificationTypeWithoutVersion)]).then(() => { + const [, updateCall, extra] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); + expect(updateCall.url).toBe("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); + expect(updateCall.method).toBe("patch"); + expect(updateCall.data).toEqual(toNTypeWithPrefixedKey(updated)); + expect(extra).toBeUndefined(); + }); + }); + + it("Update type when an additional Action is added", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const updated = structuredClone(notificationTypeWithAllProperties); + updated.Actions[1] = updated.Actions[0]; + updated.Actions[1].Language = "DE"; + + return notificationTypes.processNotificationTypes([structuredClone(updated), structuredClone(notificationTypeWithoutVersion)]).then(() => { + const [, updateCall, extra] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); + expect(updateCall.url).toBe("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); + expect(updateCall.method).toBe("patch"); + expect(updateCall.data).toEqual(toNTypeWithPrefixedKey(updated)); + expect(extra).toBeUndefined(); + }); + }); + + it("Update type when an additional DeliveryChannel is added", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const updated = structuredClone(notificationTypeWithAllProperties); + updated.DeliveryChannels[1] = updated.DeliveryChannels[0]; + updated.DeliveryChannels[1].Type = "MOBILE"; + + return notificationTypes.processNotificationTypes([structuredClone(updated), structuredClone(notificationTypeWithoutVersion)]).then(() => { + const [, updateCall, extra] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); + expect(updateCall.url).toBe("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); + expect(updateCall.method).toBe("patch"); + expect(updateCall.data).toEqual(toNTypeWithPrefixedKey(updated)); + expect(extra).toBeUndefined(); + }); + }); + + it("Update type when any individual field has changed", async () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const mutate = (target, key, value) => { + if (typeof value === "string") target[key] = value + " UPDATED"; + else if (typeof value === "boolean") target[key] = !value; + else if (typeof value === "number") target[key] = value + 1; + else return false; + return true; + }; + + const assertUpdateCall = (changed) => { + const [, updateCall, extra] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); + expect(updateCall.url).toBe("v2/NotificationType.svc/NotificationTypes(guid'26f1fad0-de4c-4869-9b4e-62f445c8a7a8')"); + expect(updateCall.method).toBe("patch"); + expect(updateCall.data).toEqual(toNTypeWithPrefixedKey(changed)); + expect(extra).toBeUndefined(); + }; + + for (const [key, value] of Object.entries(notificationTypeWithAllProperties)) { + if (key === "NotificationTypeKey" || key === "NotificationTypeVersion") continue; + const changed = structuredClone(notificationTypeWithAllProperties); + if (!mutate(changed, key, value)) continue; + await notificationTypes.processNotificationTypes([structuredClone(changed), structuredClone(notificationTypeWithoutVersion)]).then(() => assertUpdateCall(changed)); + jest.clearAllMocks(); + } + + for (const [key, value] of Object.entries(notificationTypeWithAllProperties.Templates[0])) { + const changed = structuredClone(notificationTypeWithAllProperties); + if (!mutate(changed.Templates[0], key, value)) continue; + await notificationTypes.processNotificationTypes([structuredClone(changed), structuredClone(notificationTypeWithoutVersion)]).then(() => assertUpdateCall(changed)); + jest.clearAllMocks(); + } + + for (const [key, value] of Object.entries(notificationTypeWithAllProperties.Actions[0])) { + const changed = structuredClone(notificationTypeWithAllProperties); + if (!mutate(changed.Actions[0], key, value)) continue; + await notificationTypes.processNotificationTypes([structuredClone(changed), structuredClone(notificationTypeWithoutVersion)]).then(() => assertUpdateCall(changed)); + jest.clearAllMocks(); + } + + for (const [key, value] of Object.entries(notificationTypeWithAllProperties.DeliveryChannels[0])) { + const changed = structuredClone(notificationTypeWithAllProperties); + if (!mutate(changed.DeliveryChannels[0], key, value)) continue; + await notificationTypes.processNotificationTypes([structuredClone(changed), structuredClone(notificationTypeWithoutVersion)]).then(() => assertUpdateCall(changed)); + jest.clearAllMocks(); + } + }); + + it("Update type when existing type has null inner results", () => { + httpClient.executeHttpRequest.mockReturnValue({ + data: { + d: { + results: [{ + NotificationTypeId: "test-guid-123", + NotificationTypeKey: "test-prefix/notificationTypeWithAllProperties", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: { results: null }, + Actions: { results: null }, + DeliveryChannels: { results: null } + }] + } + } + }); + + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties)]).then(() => { + const [, updateCall] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); + expect(updateCall.method).toBe("patch"); + }); + }); + }); + + describe("No Changed Needed", () => { + it("Do nothing when all types match exactly", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties), structuredClone(notificationTypeWithoutVersion)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1]).toBeUndefined(); + }); + }); + + it("Do nothing when input Templates/Actions/DeliveryChannels use OData results wrapper", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const local = structuredClone(notificationTypeWithAllProperties); + local.Templates = { results: notificationTypeWithAllProperties.Templates }; + local.Actions = { results: notificationTypeWithAllProperties.Actions }; + local.DeliveryChannels = { results: notificationTypeWithAllProperties.DeliveryChannels }; + + return notificationTypes.processNotificationTypes([local, structuredClone(notificationTypeWithoutVersion)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1]).toBeUndefined(); + }); + }); + + it("Do nothing when IsGroupable is undefined (treated as true)", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const local = structuredClone(notificationTypeWithAllProperties); + local.IsGroupable = undefined; + + return notificationTypes.processNotificationTypes([local, structuredClone(notificationTypeWithoutVersion)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1]).toBeUndefined(); + }); + }); + + it("Do nothing when Language fields are lowercase", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const local = structuredClone(notificationTypeWithAllProperties); + local.Templates[0].Language = notificationTypeWithAllProperties.Templates[0].Language.toLowerCase(); + local.Actions[0].Language = notificationTypeWithAllProperties.Actions[0].Language.toLowerCase(); + + return notificationTypes.processNotificationTypes([local, structuredClone(notificationTypeWithoutVersion)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1]).toBeUndefined(); + }); + }); + + it("Do nothing when TemplateLanguage is lowercase", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + const local = structuredClone(notificationTypeWithAllProperties); + local.Templates[0].TemplateLanguage = notificationTypeWithAllProperties.Templates[0].TemplateLanguage.toLowerCase(); + + return notificationTypes.processNotificationTypes([local, structuredClone(notificationTypeWithoutVersion)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1]).toBeUndefined(); + }); + }); + + it("Do nothing when Templates, Actions and DeliveryChannels are null in both local and remote", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingWithUndefinedTemplatesActionsAndDeliveryChannelsResponseBody); + + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithNullTemplatesActionsAndDeliveryChannels)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1]).toBeUndefined(); + }); + }); + + it("Do nothing when existing type matches local type exactly", () => { + httpClient.executeHttpRequest.mockReturnValue({ + data: { + d: { + results: [ + { + NotificationTypeId: "26f1fad0-de4c-4869-9b4e-62f445c8a7a8", + NotificationTypeKey: "test-prefix/notificationTypeWithAllProperties", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: structuredClone(notificationTypeWithAllProperties).Templates, + Actions: structuredClone(notificationTypeWithAllProperties).Actions, + DeliveryChannels: structuredClone(notificationTypeWithAllProperties).DeliveryChannels + }, + { + NotificationTypeKey: "Default", + NotificationTypeVersion: "1", + IsGroupable: true, + Templates: [], + Actions: [], + DeliveryChannels: [] + } + ] + } + } + }); + + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties)]).then(() => { + expect(httpClient.executeHttpRequest.mock.calls[1]).toBeUndefined(); + }); + }); + }); + + it("Deletes a type that is no longer in the local file", () => { + httpClient.executeHttpRequest.mockReturnValue(allExistingResponseBody); + + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties)]).then(() => { + const [, deleteCall, extra] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); + expect(deleteCall.url).toBe("v2/NotificationType.svc/NotificationTypes(guid'719d8f6a-1e07-4981-b2be-07197cec7492')"); + expect(deleteCall.method).toBe("delete"); + expect(extra).toBeUndefined(); + }); + }); + }); +}); + +function toNTypeWithPrefixedKey(ntype) { + var prefixedNtype = structuredClone(ntype); + prefixedNtype.NotificationTypeKey = testPrefix + "/" + prefixedNtype.NotificationTypeKey; + return prefixedNtype; +} diff --git a/tests/unit/lib/notifications.test.js b/tests/unit/lib/notifications.test.js new file mode 100644 index 0000000..bb976d8 --- /dev/null +++ b/tests/unit/lib/notifications.test.js @@ -0,0 +1,74 @@ +const { getNotificationDestination } = require("../../../lib/utils"); +const { buildHeadersForDestination } = require("@sap-cloud-sdk/connectivity"); +const NotifyToRest = require("../../../srv/notifyToRest"); +const { executeHttpRequest } = require("@sap-cloud-sdk/http-client"); + +jest.mock("../../../lib/utils"); +jest.mock("@sap-cloud-sdk/connectivity"); +jest.mock("@sap-cloud-sdk/http-client") + +const expectedCustomNotification = { + NotificationTypeKey: "Custom", + NotificationTypeVersion: "1", + Priority: "HIGH", + Properties: [ + { + Key: "title", + IsSensitive: false, + Language: "en", + Value: "Some Text Title", + Type: "String" + }, + { + Key: "description", + IsSensitive: false, + Language: "en", + Value: "Some Text Description", + Type: "String" + } + ], + Recipients: [{ RecipientId: "test.mail@mail.com" }] +}; + +describe("Test post notification", () => { + let alert; + let infoSpy; + + beforeEach(() => { + alert = new NotifyToRest; + infoSpy = jest.spyOn(global.console, 'info'); + getNotificationDestination.mockReturnValue(undefined); + buildHeadersForDestination.mockReturnValue(undefined); + }); + + afterEach(() => { + infoSpy.mockClear(); + }); + + it("Logs and sends when a valid notification object is posted", async () => { + executeHttpRequest.mockReturnValue(expectedCustomNotification); + await alert.postNotification(expectedCustomNotification) + + expect(infoSpy).toHaveBeenCalledWith("[notifications] -", "Sending notification of key: Custom and version: 1"); + expect(executeHttpRequest).toHaveBeenCalled(); + }) + + it.each([ + [500, false], + [404, true], + [429, false], + ])("HTTP %i error - unrecoverable is %s", async (status, unrecoverable) => { + const error = new Error(); + error.response = { message: "mocked error", status }; + executeHttpRequest.mockRejectedValue(error); + + try { + await alert.postNotification(expectedCustomNotification); + } catch (err) { + expect(!!err.unrecoverable).toBe(unrecoverable); + } + + expect(infoSpy).toHaveBeenCalledWith("[notifications] -", "Sending notification of key: Custom and version: 1"); + expect(executeHttpRequest).toHaveBeenCalled(); + }); +}) diff --git a/tests/unit/lib/utils.test.js b/tests/unit/lib/utils.test.js new file mode 100644 index 0000000..109e1ce --- /dev/null +++ b/tests/unit/lib/utils.test.js @@ -0,0 +1,476 @@ +const cds = require("@sap/cds"); +const { buildNotification, validateNotificationTypes, readFile, getNotificationDestination } = require("../../../lib/utils"); +const { existsSync, readFileSync } = require("fs"); +const { getDestination } = require("@sap-cloud-sdk/connectivity"); + +jest.mock("fs"); +jest.mock("@sap-cloud-sdk/connectivity"); + +describe("Test utils", () => { + + describe("Build notifications", () => { + describe("Default notifications", () => { + const expectedWithoutDescription = { + NotificationTypeKey: "Default", + NotificationTypeVersion: "1", + Priority: "NEUTRAL", + Properties: [ + { + Key: "title", + IsSensitive: false, + Language: "en", + Value: "Some Test Title", + Type: "String" + }, + { + Key: "description", + IsSensitive: false, + Language: "en", + Value: "", + Type: "String" + } + ], + Recipients: [{ RecipientId: "test.mail@mail.com" }] + }; + + const expectedWithDescription = { + ...expectedWithoutDescription, + Properties: [ + { + Key: "title", + IsSensitive: false, + Language: "en", + Value: "Some Test Title", + Type: "String" + }, + { + Key: "description", + IsSensitive: false, + Language: "en", + Value: "Some Test Description", + Type: "String" + } + ] + }; + + it("Build a default notification with priority", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + title: "Some Test Title", + priority: "NEUTRAL" + }) + ).toMatchObject(expectedWithoutDescription); + }); + + it("Build a default notification without priority", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + title: "Some Test Title" + }) + ).toMatchObject(expectedWithoutDescription); + }); + + it("Build a default notification with description and priority", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + title: "Some Test Title", + priority: "NEUTRAL", + description: "Some Test Description" + }) + ).toMatchObject(expectedWithDescription); + }); + + it("Build a default notification with description", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + title: "Some Test Title", + description: "Some Test Description" + }) + ).toMatchObject(expectedWithDescription); + }); + }); + + describe("Custom notifications", () => { + const properties = [{ + Key: "title", + IsSensitive: false, + Language: "en", + Value: "Some Test Title", + Type: "String" + }]; + + const baseInput = { + recipients: ["test.mail@mail.com"], + type: "TestNotificationType", + Properties: properties + }; + + const baseExpected = { + NotificationTypeKey: "notifications/TestNotificationType", + NotificationTypeVersion: "1", + Priority: "NEUTRAL", + Properties: properties, + Recipients: [{ RecipientId: "test.mail@mail.com" }] + }; + + it("Build a custom notification with properties", () => { + expect(buildNotification(baseInput)).toMatchObject(baseExpected); + }); + + it("Build a custom notification with navigation targets", () => { + expect(buildNotification({ + ...baseInput, + NavigationTargetAction: "TestTargetAction", + NavigationTargetObject: "TestTargetObject" + })).toMatchObject({ + ...baseExpected, + NavigationTargetAction: "TestTargetAction", + NavigationTargetObject: "TestTargetObject" + }); + }); + + it("Build a custom notification with a non-default priority", () => { + expect(buildNotification({ + ...baseInput, + priority: "HIGH" + })).toMatchObject({ + ...baseExpected, + Priority: "HIGH" + }); + }); + + it("Build a custom notification with a non-default priority and navigation targets", () => { + expect( + buildNotification({ + ...baseInput, + NavigationTargetAction: "TestTargetAction", + NavigationTargetObject: "TestTargetObject", + priority: "HIGH" + }) + ).toMatchObject({ + ...baseExpected, + NavigationTargetAction: "TestTargetAction", + NavigationTargetObject: "TestTargetObject", + Priority: "HIGH" + }); + }); + + it("Maps data object to Properties array", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + type: "TestNotificationType", + data: { title: "Some Test Title" } + }) + ).toMatchObject({ + ...baseExpected, + Properties: [{ + Key: "title", + Value: "Some Test Title", + Language: "en", + Type: "string" + }] + }); + }); + + it("Pass all low-level API fields through to the notification", () => { + const lowLevelFields = { + OriginId: "01234567-89ab-cdef-0123-456789abcdef", + NotificationTypeId: "01234567-89ab-cdef-0123-456789abcdef", + NavigationTargetAction: "TestTargetAction", + NavigationTargetObject: "TestTargetObject", + ProviderId: "SAMPLEPROVIDER", + ActorId: "BACKENDACTORID", + ActorDisplayText: "ActorName", + ActorImageURL: "https://some-url", + NotificationTypeTimestamp: "2022-03-15T09:58:42.807Z", + TargetParameters: [{ Key: "string", Value: "string" }] + }; + + expect(buildNotification({ + ...baseInput, + ...lowLevelFields, + priority: "HIGH" + })).toMatchObject({ + ...baseExpected, + ...lowLevelFields, + Priority: "HIGH" + }); + }); + + it("Pass partial low-level API fields through to the notification", () => { + const partialLowLevelFields = { + NotificationTypeId: "01234567-89ab-cdef-0123-456789abcdef", + NavigationTargetAction: "TestTargetAction", + NavigationTargetObject: "TestTargetObject", + ProviderId: "SAMPLEPROVIDER", + ActorId: "BACKENDACTORID", + ActorDisplayText: "ActorName", + ActorImageURL: "https://some-url", + NotificationTypeTimestamp: "2022-03-15T09:58:42.807Z", + TargetParameters: [{ Key: "string", Value: "string" }] + }; + + expect( + buildNotification({ + ...baseInput, + ...partialLowLevelFields, + priority: "HIGH" + }) + ).toMatchObject({ + ...baseExpected, + ...partialLowLevelFields, + Priority: "HIGH" + }); + }); + }); + + describe("Invalid inputs", () => { + it("Return falsy when an empty object is passed", () => { + expect(buildNotification({})).toBeFalsy(); + }); + + describe("Default notification", () => { + it("Return falsy when title is missing", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + priority: "NEUTRAL" + }) + ).toBeFalsy(); + }); + + it("Return falsy when recipients is empty", () => { + expect( + buildNotification({ + recipients: [], + title: "Some Test Title", + priority: "NEUTRAL" + }) + ).toBeFalsy(); + }); + + it("Return falsy when recipients is not an array", () => { + expect( + buildNotification({ + recipients: "invalid", + title: "Some Test Title", + priority: "NEUTRAL" + }) + ).toBeFalsy(); + }); + + it("Return falsy when priority is not a valid value", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + title: "Some Test Title", + priority: "INVALID" + }) + ).toBeFalsy(); + }); + + it("Return falsy when description is not a string", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + title: "Some Test Title", + priority: "NEUTRAL", + description: { invalid: "invalid" } + }) + ).toBeFalsy(); + }); + + it("Return falsy when title is not a string", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + title: { invalid: "invalid" }, + priority: "NEUTRAL" + }) + ).toBeFalsy(); + }); + }); + + describe("Custom notification", () => { + it("Return falsy when recipients is missing", () => { + expect( + buildNotification({ + type: "TestNotificationType" + }) + ).toBeFalsy(); + }); + + it("Return falsy when recipients is empty", () => { + expect( + buildNotification({ + recipients: [], + type: "TestNotificationType" + }) + ).toBeFalsy(); + }); + + it("Return falsy when recipients is not an array", () => { + expect( + buildNotification({ + recipients: "invalid", + type: "TestNotificationType" + }) + ).toBeFalsy(); + }); + + it("Return falsy when priority is not a valid value", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + type: "TestNotificationType", + priority: "invalid" + }) + ).toBeFalsy(); + }); + + it("Return falsy when properties is not an array", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + type: "TestNotificationType", + priority: "NEUTRAL", + properties: "invalid" + }) + ).toBeFalsy(); + }); + + it("Return falsy when navigation is not an object", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + type: "TestNotificationType", + priority: "NEUTRAL", + navigation: "invalid" + }) + ).toBeFalsy(); + }); + + it("Return falsy when payload is not an object", () => { + expect( + buildNotification({ + recipients: ["test.mail@mail.com"], + type: "TestNotificationType", + priority: "NEUTRAL", + payload: "invalid" + }) + ).toBeFalsy(); + }); + }); + }); + + it("Pass a raw notification object through with the prefix applied to the type key", () => { + const rawNotification = { + NotificationTypeKey: "TestNotificationType", + NotificationTypeVersion: "1", + Priority: "NEUTRAL", + Properties: [ + { + Key: "title", + IsSensitive: false, + Language: "en", + Value: "Some Test Title", + Type: "String" + }, + { + Key: "description", + IsSensitive: false, + Language: "en", + Value: "Some Test Description", + Type: "String" + } + ], + Recipients: [{ RecipientId: "test.mail@mail.com" }] + }; + + expect( + buildNotification({ ...rawNotification })) + .toMatchObject({ + ...rawNotification, + NotificationTypeKey: "notifications/TestNotificationType" + }); + }); + }); + + describe("Notification types validation", () => { + it("Return false when an entry is missing NotificationTypeKey", () => { + expect(validateNotificationTypes([{ NotificationTypeKey: "Test" }, { blabla: "Test2" }])).toEqual(false); + }); + + it("Return true for an empty array", () => { + expect(validateNotificationTypes([])).toBe(true); + }); + + it("Return true when all entries have NotificationTypeKey", () => { + expect(validateNotificationTypes([{ NotificationTypeKey: "Test" }, { NotificationTypeKey: "Test2" }])).toEqual(true); + }); + }); + + describe("Read file", () => { + it("Return an empty array when the file does not exist", () => { + existsSync.mockReturnValue(false); + expect(readFile("test.json")).toMatchObject([]); + }); + + it("Return the parsed file contents when the file exists", () => { + existsSync.mockReturnValue(true); + readFileSync.mockReturnValue('[{ "test": "test" }]'); + expect(readFile("test.json")).toMatchObject([{ test: "test" }]); + }); + }); + + describe("Get notification destination", () => { + it("Return the destination when it exists", async () => { + getDestination.mockReturnValue({ "mock-destination": "mock-destination" }); + expect(await getNotificationDestination()).toMatchObject({ "mock-destination": "mock-destination" }); + }); + + it("Throw an error when the destination is not found", async () => { + getDestination.mockReturnValue(undefined); + await expect(() => getNotificationDestination()).rejects.toThrow("Failed to get destination: SAP_Notifications"); + }); + }); + + describe("Configuration", () => { + it("Use GlobalUserId as the recipient key when authenticationIdentifier is set to UserUUID", () => { + cds.env.requires.notifications ??= {}; + cds.env.requires.notifications.authenticationIdentifier = "UserUUID"; + + const result = buildNotification({ + recipients: ["user-uuid-123"], + title: "Test Title" + }); + + delete cds.env.requires.notifications.authenticationIdentifier; + expect(result.Recipients[0]).toMatchObject({ GlobalUserId: "user-uuid-123" }); + }); + + it("Fall back to basename of cds.root as prefix when package.json cannot be read", () => { + let result; + jest.isolateModules(() => { + const cds = require("@sap/cds"); + const originalRoot = cds.root; + cds.env.requires.notifications ??= {}; + cds.env.requires.notifications.prefix = "$app-name"; + cds.root = "/nonexistent-path-for-testing"; + try { + const { getNotificationTypesKeyWithPrefix } = require("../../../lib/utils"); + result = getNotificationTypesKeyWithPrefix("TestType"); + } finally { + cds.root = originalRoot; + delete cds.env.requires.notifications.prefix; + } + }); + expect(result).toBe("nonexistent-path-for-testing/TestType"); + }); + }); +}); diff --git a/tests/unit/srv/notifyToRest.test.js b/tests/unit/srv/notifyToRest.test.js new file mode 100644 index 0000000..6154458 --- /dev/null +++ b/tests/unit/srv/notifyToRest.test.js @@ -0,0 +1,91 @@ +const { messages, buildNotification } = require("../../../lib/utils"); +const NotifyToRest = require("../../../srv/notifyToRest"); + +describe("Notify to rest", () => { + let notifyToRest; + + beforeEach(() => { + notifyToRest = new NotifyToRest(); + }) + + describe("Warnings", () => { + let warnSpy; + + beforeEach(() => { + warnSpy = jest.spyOn(global.console, "warn"); + }) + + afterEach(() => { + warnSpy.mockClear(); + }); + + it("No object is passed", async () => { + notifyToRest.notify(); + expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.NO_OBJECT_FOR_NOTIFY); + }); + + it("Empty object is passed", async () => { + notifyToRest.notify({}); + expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.EMPTY_OBJECT_FOR_NOTIFY); + }); + + it("Recipients or title isn't passed in default notification", async () => { + notifyToRest.notify({ dummy: true }); + expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.MANDATORY_PARAMETER_NOT_PASSED_FOR_DEFAULT_NOTIFICATION); + }); + + it("Title isn't a string in default notification", async () => { + notifyToRest.notify({ title: 1, recipients: ["abc@abc.com"] }); + expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.TITLE_IS_NOT_STRING); + }); + + it("Priority isn't valid in default notification", async () => { + notifyToRest.notify({ title: "abc", recipients: ["abc@abc.com"], priority: "abc" }); + expect(warnSpy).toHaveBeenCalledWith("[notifications] -", "Invalid priority abc. Allowed priorities are LOW, NEUTRAL, MEDIUM, HIGH"); + }); + + it("Description isn't valid in default notification", async () => { + notifyToRest.notify({ title: "abc", recipients: ["abc@abc.com"], priority: "low", description: true }); + expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.DESCRIPTION_IS_NOT_STRING); + }); + }); + + describe("Posting notifications", () => { + let postedNotification; + + beforeEach(() => { + notifyToRest.postNotification = n => postedNotification = n; + notifyToRest.init(); + }); + + it("Correct body is sent the notification should be posted", async () => { + const body = { title: "abc", recipients: ["abc@abc.com"], priority: "low" }; + await notifyToRest.notify(body); + expect(postedNotification).toMatchObject(buildNotification(body)); + }); + + it("Emit is called with an outbox request object", async () => { + const req = { event: "IncidentResolved", data: { NotificationTypeKey: "IncidentResolved", NotificationTypeVersion: "1", Priority: "NEUTRAL", Properties: [], Recipients: [] }, headers: {} }; + await notifyToRest.emit(req); + expect(postedNotification).toMatchObject(req.data); + }); + + it("Notify is called with a single object-containing type", async () => { + const body = { type: "IncidentResolved", recipients: ["abc@abc.com"], data: { title: "test" } }; + await notifyToRest.notify(body); + expect(postedNotification).toMatchObject(buildNotification(body)); + }); + + it("Notify is called with type as first arg and message as second", async () => { + await notifyToRest.notify("IncidentResolved", { recipients: ["abc@abc.com"], data: { title: "test" } }); + expect(postedNotification).toMatchObject(buildNotification({ type: "IncidentResolved", recipients: ["abc@abc.com"], data: { title: "test" } })); + }); + + it("Notify is called with a single object containing NotificationTypeKey and no type", async () => { + const body = { NotificationTypeKey: "IncidentResolved", NotificationTypeVersion: "1", Priority: "NEUTRAL", Properties: [], Recipients: [] }; + const expected = buildNotification({ ...body }); + await notifyToRest.notify(body); + expect(postedNotification).toMatchObject(expected); + }); + }); +}); From e222883a85c7b57e6cac15c1c887b9de70a87019 Mon Sep 17 00:00:00 2001 From: Eric Peairs Date: Thu, 9 Apr 2026 16:31:45 +0200 Subject: [PATCH 2/3] Node version minimum update and bot edits --- .github/workflows/node.js.yml | 2 +- lib/utils.js | 5 +++-- package.json | 3 +++ tests/bookshop/app/admin-books/webapp/manifest.json | 2 +- tests/bookshop/package.json | 2 +- tests/bookshop/srv/notification-types.json | 2 +- tests/integration/bookshop.test.js | 3 +-- tests/unit/lib/notificationTypes.test.js | 6 +++--- tests/unit/lib/notifications.test.js | 1 + 9 files changed, 15 insertions(+), 11 deletions(-) diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index 2a48c0a..9da53cb 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -16,7 +16,7 @@ jobs: strategy: matrix: - node-version: [18.x, 20.x, 22.x] + node-version: [20.x, 22.x] # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ steps: diff --git a/lib/utils.js b/lib/utils.js index 1967d88..a377927 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -97,12 +97,13 @@ function validateCustomNotifyParameters(type, recipients, properties, navigation function readFile(filePath) { - if (!existsSync(filePath)) { + const resolvedPath = cds.utils.path.resolve(cds.root, filePath); + if (!existsSync(resolvedPath)) { LOG._warn && LOG.warn(messages.TYPES_FILE_NOT_EXISTS); return []; } - return JSON.parse(readFileSync(filePath)); + return JSON.parse(readFileSync(resolvedPath)); } async function getNotificationDestination() { diff --git a/package.json b/package.json index 471385d..bf03033 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,9 @@ "chai": "^4.3.10", "express": "^5.2.1", "jest": "^29.7.0" + }, + "engines": { + "node": ">=20.0.0" }, "scripts": { "lint": "npx eslint .", diff --git a/tests/bookshop/app/admin-books/webapp/manifest.json b/tests/bookshop/app/admin-books/webapp/manifest.json index 13d7c49..4fe5129 100644 --- a/tests/bookshop/app/admin-books/webapp/manifest.json +++ b/tests/bookshop/app/admin-books/webapp/manifest.json @@ -79,7 +79,7 @@ "target": "BooksDetails" }, { - "pattern": "Books({key}/author({key2}):?query:", + "pattern": "Books({key})/author({key2}):?query:", "name": "AuthorsDetails", "target": "AuthorsDetails" } diff --git a/tests/bookshop/package.json b/tests/bookshop/package.json index 69c61ed..3f7b2a0 100644 --- a/tests/bookshop/package.json +++ b/tests/bookshop/package.json @@ -12,7 +12,7 @@ "requires": { "notifications": { "outbox": false, - "types": "tests/bookshop/srv/notification-types.json" + "types": "srv/notification-types.json" } } }, diff --git a/tests/bookshop/srv/notification-types.json b/tests/bookshop/srv/notification-types.json index 5bba84b..c3e7456 100644 --- a/tests/bookshop/srv/notification-types.json +++ b/tests/bookshop/srv/notification-types.json @@ -13,4 +13,4 @@ } ] } -] \ No newline at end of file +] diff --git a/tests/integration/bookshop.test.js b/tests/integration/bookshop.test.js index df0d52f..1ee4dff 100644 --- a/tests/integration/bookshop.test.js +++ b/tests/integration/bookshop.test.js @@ -2,10 +2,9 @@ const cds = require("@sap/cds"); const { join } = cds.utils.path; const { messages } = require("../../lib/utils"); -const { } = cds.test(join(__dirname, "../bookshop")); +cds.test(join(__dirname, "../bookshop")); describe("Notifications Integration", () => { - // Boot the bookshop app with the plugin active before all tests let alert; let infoSpy; let warnSpy; diff --git a/tests/unit/lib/notificationTypes.test.js b/tests/unit/lib/notificationTypes.test.js index 6e8c72d..9e29f11 100644 --- a/tests/unit/lib/notificationTypes.test.js +++ b/tests/unit/lib/notificationTypes.test.js @@ -349,7 +349,7 @@ describe("Managing of Notification Types", () => { it("Create Default and all new types when none exist in Work Zone", () => { httpClient.executeHttpRequest.mockReturnValue(emptyResponseBody); - notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties), structuredClone(notificationTypeWithoutVersion)]).then(() => { + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties), structuredClone(notificationTypeWithoutVersion)]).then(() => { const [, createDefault, createFirst, createSecond, extra] = httpClient.executeHttpRequest.mock.calls.map(c => c[1]); expect(createDefault.method).toBe("post"); @@ -379,7 +379,7 @@ describe("Managing of Notification Types", () => { const versionTwo = structuredClone(notificationTypeWithAllProperties); versionTwo.NotificationTypeVersion = "2"; - notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties), versionTwo, structuredClone(notificationTypeWithoutVersion)]).then(() => { + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties), versionTwo, structuredClone(notificationTypeWithoutVersion)]).then(() => { const createCall = httpClient.executeHttpRequest.mock.calls[1][1]; expect(createCall.method).toBe("post"); expect(createCall.data.NotificationTypeVersion).toBe("2"); @@ -415,7 +415,7 @@ describe("Managing of Notification Types", () => { } }); - notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties)]).then(() => { + return notificationTypes.processNotificationTypes([structuredClone(notificationTypeWithAllProperties)]).then(() => { expect(httpClient.executeHttpRequest.mock.calls[1][1].method).toBe("post"); expect(httpClient.executeHttpRequest.mock.calls[2]).toBeUndefined(); }); diff --git a/tests/unit/lib/notifications.test.js b/tests/unit/lib/notifications.test.js index bb976d8..e3c7d0f 100644 --- a/tests/unit/lib/notifications.test.js +++ b/tests/unit/lib/notifications.test.js @@ -58,6 +58,7 @@ describe("Test post notification", () => { [404, true], [429, false], ])("HTTP %i error - unrecoverable is %s", async (status, unrecoverable) => { + expect.assertions(3); const error = new Error(); error.response = { message: "mocked error", status }; executeHttpRequest.mockRejectedValue(error); From fe0a9213ce2d01460c97a965a56d18d0e1c4d597 Mon Sep 17 00:00:00 2001 From: Eric Peairs Date: Fri, 10 Apr 2026 10:12:53 +0200 Subject: [PATCH 3/3] Remove spies in favor of cds.test.log --- tests/integration/bookshop.test.js | 55 +++++----------------------- tests/unit/lib/notifications.test.js | 11 ++---- tests/unit/srv/notifyToRest.test.js | 23 ++++-------- 3 files changed, 20 insertions(+), 69 deletions(-) diff --git a/tests/integration/bookshop.test.js b/tests/integration/bookshop.test.js index 1ee4dff..972e94e 100644 --- a/tests/integration/bookshop.test.js +++ b/tests/integration/bookshop.test.js @@ -5,24 +5,13 @@ const { messages } = require("../../lib/utils"); cds.test(join(__dirname, "../bookshop")); describe("Notifications Integration", () => { + let log = cds.test.log() let alert; - let infoSpy; - let warnSpy; beforeAll(async () => { alert = await cds.connect.to("notifications"); }); - beforeEach(() => { - infoSpy = jest.spyOn(global.console, "info"); - warnSpy = jest.spyOn(global.console, "warn"); - }); - - afterEach(() => { - infoSpy.mockRestore(); - warnSpy.mockRestore(); - }); - test("Notifications service resolves to console implementation in development", async () => { expect(alert.constructor.name).toBe("NotifyToConsole"); }); @@ -38,10 +27,7 @@ describe("Notifications Integration", () => { data: { title: "test" } }); - expect(warnSpy).toHaveBeenCalledWith( - "[notifications] -", - expect.stringContaining("UnknownType is not in the notification types file") - ); + expect(log.output).toContain("UnknownType is not in the notification types file"); }); test("Sending a default notification logs to console", async () => { @@ -51,30 +37,17 @@ describe("Notifications Integration", () => { description: "A new book has been added to the catalogue" }); - expect(infoSpy).toHaveBeenCalledWith( - "[notifications] -", - expect.any(String), - expect.any(String), - expect.objectContaining({ - NotificationTypeKey: "Default", - Priority: "NEUTRAL", - Recipients: [{ RecipientId: "reader@bookshop.com" }], - Properties: expect.arrayContaining([ - expect.objectContaining({ Key: "title", Value: "New book arrived" }) - ]) - }), - expect.any(String) - ); + expect(log.output).toContain("Notification:"); + expect(log.output).toContain("NotificationTypeKey: 'Default'"); + expect(log.output).toContain("RecipientId: 'reader@bookshop.com'"); + expect(log.output).toContain("Value: 'New book arrived'"); }); test("Sending a notification with no arguments warns and does nothing", async () => { await alert.notify(); - expect(warnSpy).toHaveBeenCalledWith( - "[notifications] -", - messages.NO_OBJECT_FOR_NOTIFY - ); - expect(infoSpy).not.toHaveBeenCalled(); + expect(log.output).toContain(messages.NO_OBJECT_FOR_NOTIFY); + expect(log.output).not.toContain("Notification:"); }); test("Custom typed notification uses prefixed type key from types file", async () => { @@ -83,15 +56,7 @@ describe("Notifications Integration", () => { data: { title: "Moby Dick", buyer: "reader@bookshop.com" } }); - expect(infoSpy).toHaveBeenCalledWith( - "[notifications] -", - expect.any(String), - expect.any(String), - expect.objectContaining({ - NotificationTypeKey: "bookshop/BookOrdered" - }), - expect.any(String) - ); - expect(warnSpy).not.toHaveBeenCalled(); + expect(log.output).toContain("bookshop/BookOrdered"); + expect(log.output).not.toContain("is not in the notification types file"); }); }); \ No newline at end of file diff --git a/tests/unit/lib/notifications.test.js b/tests/unit/lib/notifications.test.js index e3c7d0f..695b226 100644 --- a/tests/unit/lib/notifications.test.js +++ b/tests/unit/lib/notifications.test.js @@ -31,25 +31,20 @@ const expectedCustomNotification = { }; describe("Test post notification", () => { + let log = cds.test.log() let alert; - let infoSpy; beforeEach(() => { alert = new NotifyToRest; - infoSpy = jest.spyOn(global.console, 'info'); getNotificationDestination.mockReturnValue(undefined); buildHeadersForDestination.mockReturnValue(undefined); }); - afterEach(() => { - infoSpy.mockClear(); - }); - it("Logs and sends when a valid notification object is posted", async () => { executeHttpRequest.mockReturnValue(expectedCustomNotification); await alert.postNotification(expectedCustomNotification) - expect(infoSpy).toHaveBeenCalledWith("[notifications] -", "Sending notification of key: Custom and version: 1"); + expect(log.output).toContain("Sending notification of key: Custom and version: 1"); expect(executeHttpRequest).toHaveBeenCalled(); }) @@ -69,7 +64,7 @@ describe("Test post notification", () => { expect(!!err.unrecoverable).toBe(unrecoverable); } - expect(infoSpy).toHaveBeenCalledWith("[notifications] -", "Sending notification of key: Custom and version: 1"); + expect(log.output).toContain("Sending notification of key: Custom and version: 1"); expect(executeHttpRequest).toHaveBeenCalled(); }); }) diff --git a/tests/unit/srv/notifyToRest.test.js b/tests/unit/srv/notifyToRest.test.js index 6154458..887e3f9 100644 --- a/tests/unit/srv/notifyToRest.test.js +++ b/tests/unit/srv/notifyToRest.test.js @@ -2,6 +2,7 @@ const { messages, buildNotification } = require("../../../lib/utils"); const NotifyToRest = require("../../../srv/notifyToRest"); describe("Notify to rest", () => { + let log = cds.test.log() let notifyToRest; beforeEach(() => { @@ -9,44 +10,34 @@ describe("Notify to rest", () => { }) describe("Warnings", () => { - let warnSpy; - - beforeEach(() => { - warnSpy = jest.spyOn(global.console, "warn"); - }) - - afterEach(() => { - warnSpy.mockClear(); - }); - it("No object is passed", async () => { notifyToRest.notify(); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.NO_OBJECT_FOR_NOTIFY); + expect(log.output).toContain(messages.NO_OBJECT_FOR_NOTIFY); }); it("Empty object is passed", async () => { notifyToRest.notify({}); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.EMPTY_OBJECT_FOR_NOTIFY); + expect(log.output).toContain(messages.EMPTY_OBJECT_FOR_NOTIFY); }); it("Recipients or title isn't passed in default notification", async () => { notifyToRest.notify({ dummy: true }); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.MANDATORY_PARAMETER_NOT_PASSED_FOR_DEFAULT_NOTIFICATION); + expect(log.output).toContain(messages.MANDATORY_PARAMETER_NOT_PASSED_FOR_DEFAULT_NOTIFICATION); }); it("Title isn't a string in default notification", async () => { notifyToRest.notify({ title: 1, recipients: ["abc@abc.com"] }); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.TITLE_IS_NOT_STRING); + expect(log.output).toContain(messages.TITLE_IS_NOT_STRING); }); it("Priority isn't valid in default notification", async () => { notifyToRest.notify({ title: "abc", recipients: ["abc@abc.com"], priority: "abc" }); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", "Invalid priority abc. Allowed priorities are LOW, NEUTRAL, MEDIUM, HIGH"); + expect(log.output).toContain("Invalid priority abc. Allowed priorities are LOW, NEUTRAL, MEDIUM, HIGH"); }); it("Description isn't valid in default notification", async () => { notifyToRest.notify({ title: "abc", recipients: ["abc@abc.com"], priority: "low", description: true }); - expect(warnSpy).toHaveBeenCalledWith("[notifications] -", messages.DESCRIPTION_IS_NOT_STRING); + expect(log.output).toContain(messages.DESCRIPTION_IS_NOT_STRING); }); });