@luigi-project/testing-utilities 2.14.2-dev.202407240028 → 2.14.2-dev.202407260027

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,20 +79,19 @@ describe('Another test using cypress', () => {
79
79
  cy.get('.pathExists').click().then(() => {
80
80
  luigiMockUtil.mockPathExists('/test', false);
81
81
  });
82
- cy.getAllSessionStorage().then((result: any) => {
83
- expect(result).to.deep.equal({
84
- "http://localhost:4200": {
85
- luigiMockData: '{"pathExists":{"/test":false}}'
86
- },
87
- });
88
- })
82
+ cy.getAllSessionStorage().then((storage: any) => {
83
+ const result = luigiMockUtil.getCleanSessionStorageData(storage);
84
+
85
+ expect(result).to.contains(luigiMockUtil.getMockedPathExistsOutput('/test', false));
86
+ });
89
87
  });
90
88
 
91
89
  it('should mock context update', () => {
90
+ const visualizationContainerId = luigiMockUtil.getVisualizationContainerId();
92
91
  const context = {ctxKey: 'ctxValue'};
93
92
 
94
93
  luigiMockUtil.mockContext(context);
95
- cy.get('#luigi-debug-vis-cnt').contains('{"msg":"luigi.get-context","context":{"ctxKey":"ctxValue"}}');
94
+ cy.get('#' + visualizationContainerId).contains(luigiMockUtil.getMockedContextOutput(context));
96
95
  });
97
96
  });
98
97
  ```
@@ -113,22 +112,25 @@ describe('Another test using nightwatch', function () {
113
112
  await browser.expect.element('.pathExists').to.be.present;
114
113
  await browser.element('.pathExists').click().then(() => {
115
114
  luigiMockUtil.mockPathExists('/test', false);
116
- browser.execute(() => window.sessionStorage.getItem('luigiMockData'), [], function (result) {
117
- expect(result.value).to.contains('{"pathExists":{"/test":false}}');
115
+ browser.execute(() => window.sessionStorage, [], function (storage) {
116
+ const result = luigiMockUtil.getCleanSessionStorageData(storage.value);
117
+
118
+ expect(result).to.contains(luigiMockUtil.getMockedPathExistsOutput('/test', false));
118
119
  });
119
120
  });
120
121
  });
121
122
 
122
123
  it('should mock context update', async () => {
124
+ const visualizationContainerId = luigiMockUtil.getVisualizationContainerId();
123
125
  const context = {ctxKey: 'ctxValue'};
124
126
 
125
127
  await luigiMockUtil.mockContext(context);
126
- // Wait until '#luigi-debug-vis-cnt' element is present
127
- await browser.waitForElementPresent('#luigi-debug-vis-cnt', undefined, undefined, false, () => {
128
- const wrapper = browser.expect.element('#luigi-debug-vis-cnt');
128
+ // Wait until Luigi visualization container is present
129
+ await browser.waitForElementPresent('#' + visualizationContainerId, undefined, undefined, false, () => {
130
+ const wrapper = browser.expect.element('#' + visualizationContainerId);
129
131
 
130
132
  wrapper.to.be.present;
131
- wrapper.text.to.contains('{"msg":"luigi.get-context","context":{"ctxKey":"ctxValue"}}');
133
+ wrapper.text.to.contains(luigiMockUtil.getMockedContextOutput(context));
132
134
  });
133
135
  });
134
136
 
@@ -158,21 +160,23 @@ describe('Another test using webdriverio', () => {
158
160
  // Wait until session storage item is set
159
161
  await browser.setTimeout(defaultTimeout);
160
162
 
161
- const result = await browser.execute(() => window.sessionStorage.getItem('luigiMockData'));
163
+ const storage = await browser.execute(() => window.sessionStorage);
164
+ const result = await luigiMockUtil.getCleanSessionStorageData(storage);
162
165
 
163
- await expect(result).toEqual('{"pathExists":{"/test":false}}');
166
+ await expect(result).toContain(luigiMockUtil.getMockedPathExistsOutput('/test', false));
164
167
  });
165
168
 
166
169
  it('should mock context update', async () => {
167
170
  luigiMockUtil = new LuigiMockUtil(browser);
168
171
 
172
+ const visualizationContainerId = luigiMockUtil.getVisualizationContainerId();
169
173
  const context = {ctxKey: 'ctxValue'};
170
174
 
171
175
  await browser.url(baseUrl);
172
176
  await luigiMockUtil.mockContext(context);
173
- // Wait until '#luigi-debug-vis-cnt' element is present
177
+ // Wait until Luigi visualization container is present
174
178
  await browser.setTimeout(defaultTimeout);
175
- await expect($('#luigi-debug-vis-cnt')).toHaveHTML(expect.stringContaining('{"msg":"luigi.get-context","context":{"ctxKey":"ctxValue"}}'));
179
+ await expect($('#' + visualizationContainerId)).toHaveHTML(expect.stringContaining(luigiMockUtil.getMockedContextOutput(context)));
176
180
  });
177
181
  });
178
182
  ```
@@ -221,25 +225,27 @@ describe('Another test using puppeteer ->', () => {
221
225
  // Wait until session storage item is set
222
226
  await new Promise(resolve => setTimeout(resolve, 500));
223
227
 
224
- const result = await page.evaluate(() => window.sessionStorage.getItem('luigiMockData'));
228
+ const storage = await page.evaluate(() => JSON.stringify(window.sessionStorage));
229
+ const result = await luigiMockUtil.getCleanSessionStorageData(storage);
225
230
 
226
- await expect(result).toContain('{"pathExists":{"/test":false}}');
231
+ await expect(result).toContain(luigiMockUtil.getMockedPathExistsOutput('/test', false));
227
232
  });
228
233
  });
229
234
  });
230
235
 
231
236
  it('should mock context update', async () => {
237
+ const visualizationContainerId = luigiMockUtil.getVisualizationContainerId();
232
238
  const context = {ctxKey: 'ctxValue'};
233
239
 
234
240
  await luigiMockUtil.mockContext(context);
235
- // Wait until '#luigi-debug-vis-cnt' element is present
236
- await page.waitForSelector('#luigi-debug-vis-cnt').then(async () => {
241
+ // Wait until Luigi visualization container is present
242
+ await page.waitForSelector('#' + visualizationContainerId).then(async () => {
237
243
  const result = await page
238
- .locator('#luigi-debug-vis-cnt div:nth-child(1)')
244
+ .locator(`#${visualizationContainerId} div:nth-child(1)`)
239
245
  .map(div => div.innerText)
240
246
  .wait();
241
247
 
242
- expect(result).toContain('{"msg":"luigi.get-context","context":{"ctxKey":"ctxValue"}}');
248
+ expect(result).toContain(luigiMockUtil.getMockedContextOutput(context));
243
249
  });
244
250
  });
245
251
  });
@@ -247,7 +253,11 @@ describe('Another test using puppeteer ->', () => {
247
253
 
248
254
  #### Functions provided
249
255
  - **mockContext**: Mocks the context by sending Luigi context messages with the desired mocked context as parameter.
250
- - **mockPathExists**: This method serves as a mock for the Luigi Client `pathExists()` function. It is used in e2e tests when component being tested utilizes a call to `LuigiClient.linkManager().pathExists()`
256
+ - **mockPathExists**: This method serves as a mock for the Luigi Client `pathExists()` function. It is used in e2e tests when component being tested utilizes a call to `LuigiClient.linkManager().pathExists()`.
251
257
  - **modalOpenedWithTitle**: Checks on the printed DOM Luigi message responses for a modal with given title being opened. In such a case, a message would be printed containing a `modal.title`. Returns `false` if such element was not found.
252
- - **getMSG**: Return list of messages, representing message elements added in the DOM for testing.
253
- - **parseLuigiMockedMessages**: Parses the elements added by LuigiMockModule into the DOM and assigns them to the local messages variable
258
+ - **getMockedContextOutput**: Returns output of 'mockContext' method with given data.
259
+ - **getMockedPathExistsOutput**: Returns output of 'mockPathExists' method with given arguments.
260
+ - **getCleanSessionStorageData**: Returns parsed session storage data used for testing.
261
+ - **getVisualizationContainerId**: Returns ID of Luigi visualization container added in the DOM for testing.
262
+ - **getMSG**: Returns list of messages, representing message elements added in the DOM for testing.
263
+ - **parseLuigiMockedMessages**: Parses the elements added by LuigiMockModule into the DOM and assigns them to the local messages variable.
@@ -135,17 +135,18 @@ export class LuigiMockEngine {
135
135
  * which holds data that is useful for e2e testing.
136
136
  */
137
137
  static visualize(data) {
138
- let luigiVisualizationContainer = document.querySelector('#luigi-debug-vis-cnt');
138
+ const visualizationContainerId = 'luigi-debug-vis-cnt';
139
+ const dataWrapper = document.createElement('div');
140
+ let luigiVisualizationContainer = document.querySelector('#' + visualizationContainerId);
139
141
  // Construct element structure if not already constructed
140
142
  if (!luigiVisualizationContainer) {
141
143
  luigiVisualizationContainer = document.createElement('div');
142
- luigiVisualizationContainer.setAttribute('id', 'luigi-debug-vis-cnt');
144
+ luigiVisualizationContainer.setAttribute('id', visualizationContainerId);
143
145
  // Hide the added DOM element to avoid interferring/overlapping with other elements during testing.
144
146
  luigiVisualizationContainer.setAttribute('style', 'display:none');
145
147
  document.body.appendChild(luigiVisualizationContainer);
146
148
  }
147
- const line = document.createElement('div');
148
- line.textContent = data;
149
- luigiVisualizationContainer.appendChild(line);
149
+ dataWrapper.textContent = data;
150
+ luigiVisualizationContainer.appendChild(dataWrapper);
150
151
  }
151
152
  }
@@ -1,13 +1,10 @@
1
1
  export declare class LuigiMockUtil {
2
+ private sessionStorageItemName;
3
+ private visualizationContainerId;
2
4
  private messages;
3
5
  private browser;
4
6
  private win;
5
7
  constructor(browser: any, win?: any);
6
- /**
7
- * Returns the global window object.
8
- * @returns the glboal win object
9
- */
10
- private getGlobalThis;
11
8
  /**
12
9
  * Parses the elements added by LuigiMockModule into the DOM and assigns them to the local this.messages variable
13
10
  * @returns {Promise<void>} - A Promise that resolves when parsing is complete.
@@ -17,7 +14,7 @@ export declare class LuigiMockUtil {
17
14
  * Mocks the context by sending luigi context messages with the desired mocked context as parameter.
18
15
  * @param mockContext an object representing the context to be mocked
19
16
  */
20
- mockContext: (mockContext: Record<string, any>) => void;
17
+ mockContext(mockContext: Record<string, any>): void;
21
18
  /**
22
19
  * This method serves as a mock for the luigi client pathExists() function.
23
20
  * It is used in e2e tests when component being tested utilizes a call to `LuigiClient.linkManager().pathExists()`
@@ -34,7 +31,7 @@ export declare class LuigiMockUtil {
34
31
  * await mockPathExists('pathToCheck', false);
35
32
  *
36
33
  */
37
- mockPathExists: (path: string, exists: boolean) => void;
34
+ mockPathExists(path: string, exists: boolean): void;
38
35
  /**
39
36
  * Checks on the printed DOM Luigi message responses for a modal with given title
40
37
  * having been opened. In such a case a message would be printed containing a modal.title.
@@ -63,7 +60,37 @@ export declare class LuigiMockUtil {
63
60
  */
64
61
  modalOpenedWithTitle(title: string): Promise<boolean>;
65
62
  /**
66
- * Return list of messages, representing message elements added in the DOM for testing.
63
+ * Returns output of 'mockContext' method with given data.
64
+ * @param {Object} context - Object representing the context to be mocked.
65
+ * @returns {string} - Stringified output of 'mockContext' method.
66
+ */
67
+ getMockedContextOutput(context: Record<string, any>): string;
68
+ /**
69
+ * Returns output of 'mockPathExists' method with given arguments.
70
+ * @param {string} path - The path for which mock data is to be set.
71
+ * @param {boolean} exists - Boolean indicating whether the path exists.
72
+ * @returns {string} - Stringified output of 'mockPathExists' method.
73
+ */
74
+ getMockedPathExistsOutput(path: string, exists: boolean): string;
75
+ /**
76
+ * Returns parsed session storage data used for testing.
77
+ * @param {Object} data - Object or string representing the data to be cleaned.
78
+ * @returns {string} - Stringified session storage data.
79
+ */
80
+ getCleanSessionStorageData(data: any): string;
81
+ /**
82
+ * Returns ID of Luigi visualization container added in the DOM for testing.
83
+ * @returns {string} - ID of Luigi visualization container.
84
+ */
85
+ getVisualizationContainerId(): string;
86
+ /**
87
+ * Returns list of messages, representing message elements added in the DOM for testing.
88
+ * @returns {Array} - Array of message elements.
67
89
  */
68
90
  getMSG(): any[];
91
+ /**
92
+ * Returns the global window object.
93
+ * @returns the global win object
94
+ */
95
+ private getGlobalThis;
69
96
  }
@@ -1,101 +1,11 @@
1
1
  export class LuigiMockUtil {
2
2
  constructor(browser, win) {
3
- /**
4
- * Mocks the context by sending luigi context messages with the desired mocked context as parameter.
5
- * @param mockContext an object representing the context to be mocked
6
- */
7
- this.mockContext = (mockContext) => {
8
- const window = this.getGlobalThis();
9
- const postMessageToLuigi = (context) => {
10
- window.postMessage({ msg: 'luigi.get-context', context }, '*');
11
- return Object.assign(Object.assign({}, context), { windowMessage: 'isPosted' });
12
- };
13
- try {
14
- switch (true) {
15
- case 'evaluate' in this.browser:
16
- this.browser.evaluate(postMessageToLuigi, mockContext);
17
- break;
18
- case 'execute' in this.browser:
19
- this.browser.execute(postMessageToLuigi, mockContext);
20
- break;
21
- case 'executeScript' in this.browser:
22
- this.browser.executeScript(postMessageToLuigi, mockContext);
23
- break;
24
- default:
25
- this.browser(postMessageToLuigi.bind(this, mockContext));
26
- break;
27
- }
28
- }
29
- catch (error) {
30
- console.debug('Failed to mock context: ', error);
31
- }
32
- };
33
- /**
34
- * This method serves as a mock for the luigi client pathExists() function.
35
- * It is used in e2e tests when component being tested utilizes a call to `LuigiClient.linkManager().pathExists()`
36
- *
37
- * @param path the path to check
38
- * @param exists mocked boolean representing if path should exist or not
39
- * @example For the following call in your angular component:
40
- * `LuigiClient.linkManager().pathExists('pathToCheck')`
41
- *
42
- * // You need to call the following to mock pathExists() returning `true` for a given 'pathToCheck':
43
- * await mockPathExists('pathToCheck', true);
44
- *
45
- * // You need to call the following to mock pathExists() returning `false` for a given 'pathToCheck':
46
- * await mockPathExists('pathToCheck', false);
47
- *
48
- */
49
- this.mockPathExists = (path, exists) => {
50
- const window = this.getGlobalThis();
51
- const mockContext = { path, exists };
52
- /**
53
- * Sets the path exists mock data in sessionStorage.
54
- * @param {string} path - The path for which mock data is to be set.
55
- * @param {boolean} exists - Boolean indicating whether the path exists.
56
- * @returns {Object} - Object indicating session storage item.
57
- */
58
- const setPathExistsMockData = (context) => {
59
- window.sessionStorage.clear();
60
- const pathExistsMockData = {
61
- pathExists: {
62
- [context['path']]: context['exists']
63
- }
64
- };
65
- window.sessionStorage.setItem('luigiMockData', JSON.stringify(pathExistsMockData));
66
- return Object.assign(Object.assign({}, pathExistsMockData), { sessionItem: 'isStored' });
67
- };
68
- try {
69
- switch (true) {
70
- case 'evaluate' in this.browser:
71
- this.browser.evaluate(setPathExistsMockData, mockContext);
72
- break;
73
- case 'execute' in this.browser:
74
- this.browser.execute(setPathExistsMockData, mockContext);
75
- break;
76
- case 'executeScript' in this.browser:
77
- this.browser.executeScript(setPathExistsMockData, mockContext);
78
- break;
79
- default:
80
- this.browser(setPathExistsMockData.bind(this, mockContext));
81
- break;
82
- }
83
- }
84
- catch (error) {
85
- console.debug('Failed to mock path exists: ', error);
86
- }
87
- };
3
+ this.sessionStorageItemName = 'luigiMockData';
4
+ this.visualizationContainerId = 'luigi-debug-vis-cnt';
88
5
  this.messages = [];
89
6
  this.browser = browser;
90
7
  this.win = win;
91
8
  }
92
- /**
93
- * Returns the global window object.
94
- * @returns the glboal win object
95
- */
96
- getGlobalThis() {
97
- return this.win || globalThis;
98
- }
99
9
  /**
100
10
  * Parses the elements added by LuigiMockModule into the DOM and assigns them to the local this.messages variable
101
11
  * @returns {Promise<void>} - A Promise that resolves when parsing is complete.
@@ -103,7 +13,7 @@ export class LuigiMockUtil {
103
13
  async parseLuigiMockedMessages() {
104
14
  const window = this.getGlobalThis();
105
15
  const getTextNodeValues = () => {
106
- const debugCtn = window.getElementById('luigi-debug-vis-cnt');
16
+ const debugCtn = window.getElementById(this.visualizationContainerId);
107
17
  return Array.from((debugCtn === null || debugCtn === void 0 ? void 0 : debugCtn.childNodes) || []).map((item) => item.textContent || '');
108
18
  };
109
19
  let textElements;
@@ -137,6 +47,91 @@ export class LuigiMockUtil {
137
47
  console.debug('Failed to parse luigi mocked messages: ', error);
138
48
  }
139
49
  }
50
+ /**
51
+ * Mocks the context by sending luigi context messages with the desired mocked context as parameter.
52
+ * @param mockContext an object representing the context to be mocked
53
+ */
54
+ mockContext(mockContext) {
55
+ const window = this.getGlobalThis();
56
+ const postMessageToLuigi = (context) => {
57
+ window.postMessage({ msg: 'luigi.get-context', context }, '*');
58
+ return Object.assign(Object.assign({}, context), { windowMessage: 'isPosted' });
59
+ };
60
+ try {
61
+ switch (true) {
62
+ case 'evaluate' in this.browser:
63
+ this.browser.evaluate(postMessageToLuigi, mockContext);
64
+ break;
65
+ case 'execute' in this.browser:
66
+ this.browser.execute(postMessageToLuigi, mockContext);
67
+ break;
68
+ case 'executeScript' in this.browser:
69
+ this.browser.executeScript(postMessageToLuigi, mockContext);
70
+ break;
71
+ default:
72
+ this.browser(postMessageToLuigi.bind(this, mockContext));
73
+ break;
74
+ }
75
+ }
76
+ catch (error) {
77
+ console.debug('Failed to mock context: ', error);
78
+ }
79
+ }
80
+ /**
81
+ * This method serves as a mock for the luigi client pathExists() function.
82
+ * It is used in e2e tests when component being tested utilizes a call to `LuigiClient.linkManager().pathExists()`
83
+ *
84
+ * @param path the path to check
85
+ * @param exists mocked boolean representing if path should exist or not
86
+ * @example For the following call in your angular component:
87
+ * `LuigiClient.linkManager().pathExists('pathToCheck')`
88
+ *
89
+ * // You need to call the following to mock pathExists() returning `true` for a given 'pathToCheck':
90
+ * await mockPathExists('pathToCheck', true);
91
+ *
92
+ * // You need to call the following to mock pathExists() returning `false` for a given 'pathToCheck':
93
+ * await mockPathExists('pathToCheck', false);
94
+ *
95
+ */
96
+ mockPathExists(path, exists) {
97
+ const window = this.getGlobalThis();
98
+ const mockContext = { path, exists };
99
+ /**
100
+ * Sets the path exists mock data in sessionStorage.
101
+ * @param {string} path - The path for which mock data is to be set.
102
+ * @param {boolean} exists - Boolean indicating whether the path exists.
103
+ * @returns {Object} - Object indicating session storage item.
104
+ */
105
+ const setPathExistsMockData = (context) => {
106
+ window.sessionStorage.clear();
107
+ const pathExistsMockData = {
108
+ pathExists: {
109
+ [context['path']]: context['exists']
110
+ }
111
+ };
112
+ window.sessionStorage.setItem(this.sessionStorageItemName, JSON.stringify(pathExistsMockData));
113
+ return Object.assign(Object.assign({}, pathExistsMockData), { sessionItem: 'isStored' });
114
+ };
115
+ try {
116
+ switch (true) {
117
+ case 'evaluate' in this.browser:
118
+ this.browser.evaluate(setPathExistsMockData, mockContext);
119
+ break;
120
+ case 'execute' in this.browser:
121
+ this.browser.execute(setPathExistsMockData, mockContext);
122
+ break;
123
+ case 'executeScript' in this.browser:
124
+ this.browser.executeScript(setPathExistsMockData, mockContext);
125
+ break;
126
+ default:
127
+ this.browser(setPathExistsMockData.bind(this, mockContext));
128
+ break;
129
+ }
130
+ }
131
+ catch (error) {
132
+ console.debug('Failed to mock path exists: ', error);
133
+ }
134
+ }
140
135
  /**
141
136
  * Checks on the printed DOM Luigi message responses for a modal with given title
142
137
  * having been opened. In such a case a message would be printed containing a modal.title.
@@ -186,9 +181,55 @@ export class LuigiMockUtil {
186
181
  return false;
187
182
  }
188
183
  /**
189
- * Return list of messages, representing message elements added in the DOM for testing.
184
+ * Returns output of 'mockContext' method with given data.
185
+ * @param {Object} context - Object representing the context to be mocked.
186
+ * @returns {string} - Stringified output of 'mockContext' method.
187
+ */
188
+ getMockedContextOutput(context) {
189
+ return `{"msg":"luigi.get-context","context":${JSON.stringify(context)}}`;
190
+ }
191
+ /**
192
+ * Returns output of 'mockPathExists' method with given arguments.
193
+ * @param {string} path - The path for which mock data is to be set.
194
+ * @param {boolean} exists - Boolean indicating whether the path exists.
195
+ * @returns {string} - Stringified output of 'mockPathExists' method.
196
+ */
197
+ getMockedPathExistsOutput(path, exists) {
198
+ return JSON.stringify({ [this.sessionStorageItemName]: { pathExists: { [path]: exists } } }).slice(1, -1);
199
+ }
200
+ /**
201
+ * Returns parsed session storage data used for testing.
202
+ * @param {Object} data - Object or string representing the data to be cleaned.
203
+ * @returns {string} - Stringified session storage data.
204
+ */
205
+ getCleanSessionStorageData(data) {
206
+ if (typeof data === 'string') {
207
+ data = JSON.parse(data);
208
+ }
209
+ return JSON.stringify(data)
210
+ .replace(/\\/g, '')
211
+ .replace(/"{/g, '{')
212
+ .replace(/}"/g, '}');
213
+ }
214
+ /**
215
+ * Returns ID of Luigi visualization container added in the DOM for testing.
216
+ * @returns {string} - ID of Luigi visualization container.
217
+ */
218
+ getVisualizationContainerId() {
219
+ return this.visualizationContainerId;
220
+ }
221
+ /**
222
+ * Returns list of messages, representing message elements added in the DOM for testing.
223
+ * @returns {Array} - Array of message elements.
190
224
  */
191
225
  getMSG() {
192
226
  return this.messages;
193
227
  }
228
+ /**
229
+ * Returns the global window object.
230
+ * @returns the global win object
231
+ */
232
+ getGlobalThis() {
233
+ return this.win || globalThis;
234
+ }
194
235
  }
package/package.json CHANGED
@@ -19,7 +19,7 @@
19
19
  "microfrontends",
20
20
  "testing"
21
21
  ],
22
- "version": "2.14.2-dev.202407240028",
22
+ "version": "2.14.2-dev.202407260027",
23
23
  "engines": {
24
24
  "node": ">=18"
25
25
  }