codeceptjs 3.6.0-beta.1.ai-healers → 3.6.0

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.
Files changed (129) hide show
  1. package/README.md +2 -2
  2. package/bin/codecept.js +2 -1
  3. package/docs/webapi/dontSeeTraffic.mustache +13 -0
  4. package/docs/webapi/flushNetworkTraffics.mustache +5 -0
  5. package/docs/webapi/grabRecordedNetworkTraffics.mustache +10 -0
  6. package/docs/webapi/seeTraffic.mustache +36 -0
  7. package/docs/webapi/startRecordingTraffic.mustache +8 -0
  8. package/docs/webapi/startRecordingWebSocketMessages.mustache +8 -0
  9. package/docs/webapi/stopRecordingTraffic.mustache +5 -0
  10. package/docs/webapi/stopRecordingWebSocketMessages.mustache +7 -0
  11. package/docs/webapi/waitForCookie.mustache +9 -0
  12. package/lib/actor.js +6 -3
  13. package/lib/command/dryRun.js +44 -13
  14. package/lib/helper/Appium.js +36 -12
  15. package/lib/helper/Expect.js +11 -8
  16. package/lib/helper/JSONResponse.js +8 -8
  17. package/lib/helper/MockServer.js +221 -0
  18. package/lib/helper/Playwright.js +107 -371
  19. package/lib/helper/Puppeteer.js +404 -71
  20. package/lib/helper/REST.js +4 -1
  21. package/lib/helper/WebDriver.js +189 -13
  22. package/lib/helper/errors/ElementAssertion.js +38 -0
  23. package/lib/helper/extras/PlaywrightReactVueLocator.js +6 -1
  24. package/lib/helper/network/actions.js +123 -0
  25. package/lib/helper/network/utils.js +187 -0
  26. package/lib/locator.js +36 -5
  27. package/lib/plugin/coverage.js +112 -99
  28. package/lib/step.js +3 -1
  29. package/package.json +48 -37
  30. package/typings/index.d.ts +19 -2
  31. package/typings/promiseBasedTypes.d.ts +505 -41
  32. package/typings/types.d.ts +609 -56
  33. package/docs/advanced.md +0 -351
  34. package/docs/ai.md +0 -365
  35. package/docs/api.md +0 -323
  36. package/docs/basics.md +0 -979
  37. package/docs/bdd.md +0 -539
  38. package/docs/best.md +0 -237
  39. package/docs/books.md +0 -37
  40. package/docs/bootstrap.md +0 -135
  41. package/docs/build/AI.js +0 -124
  42. package/docs/build/ApiDataFactory.js +0 -410
  43. package/docs/build/Appium.js +0 -2027
  44. package/docs/build/Expect.js +0 -422
  45. package/docs/build/FileSystem.js +0 -228
  46. package/docs/build/GraphQL.js +0 -229
  47. package/docs/build/GraphQLDataFactory.js +0 -309
  48. package/docs/build/JSONResponse.js +0 -338
  49. package/docs/build/Mochawesome.js +0 -71
  50. package/docs/build/Nightmare.js +0 -2152
  51. package/docs/build/OpenAI.js +0 -126
  52. package/docs/build/Playwright.js +0 -5110
  53. package/docs/build/Protractor.js +0 -2706
  54. package/docs/build/Puppeteer.js +0 -3905
  55. package/docs/build/REST.js +0 -344
  56. package/docs/build/TestCafe.js +0 -2125
  57. package/docs/build/WebDriver.js +0 -4240
  58. package/docs/changelog.md +0 -2572
  59. package/docs/commands.md +0 -266
  60. package/docs/community-helpers.md +0 -58
  61. package/docs/configuration.md +0 -157
  62. package/docs/continuous-integration.md +0 -22
  63. package/docs/custom-helpers.md +0 -306
  64. package/docs/data.md +0 -379
  65. package/docs/detox.md +0 -235
  66. package/docs/docker.md +0 -136
  67. package/docs/email.md +0 -183
  68. package/docs/examples.md +0 -149
  69. package/docs/heal.md +0 -186
  70. package/docs/helpers/ApiDataFactory.md +0 -266
  71. package/docs/helpers/Appium.md +0 -1374
  72. package/docs/helpers/Detox.md +0 -586
  73. package/docs/helpers/Expect.md +0 -275
  74. package/docs/helpers/FileSystem.md +0 -152
  75. package/docs/helpers/GraphQL.md +0 -151
  76. package/docs/helpers/GraphQLDataFactory.md +0 -226
  77. package/docs/helpers/JSONResponse.md +0 -254
  78. package/docs/helpers/Mochawesome.md +0 -8
  79. package/docs/helpers/MockRequest.md +0 -377
  80. package/docs/helpers/Nightmare.md +0 -1305
  81. package/docs/helpers/OpenAI.md +0 -70
  82. package/docs/helpers/Playwright.md +0 -2759
  83. package/docs/helpers/Polly.md +0 -44
  84. package/docs/helpers/Protractor.md +0 -1769
  85. package/docs/helpers/Puppeteer-firefox.md +0 -86
  86. package/docs/helpers/Puppeteer.md +0 -2317
  87. package/docs/helpers/REST.md +0 -218
  88. package/docs/helpers/TestCafe.md +0 -1321
  89. package/docs/helpers/WebDriver.md +0 -2547
  90. package/docs/hooks.md +0 -340
  91. package/docs/index.md +0 -111
  92. package/docs/installation.md +0 -75
  93. package/docs/internal-api.md +0 -266
  94. package/docs/locators.md +0 -339
  95. package/docs/mobile-react-native-locators.md +0 -67
  96. package/docs/mobile.md +0 -338
  97. package/docs/pageobjects.md +0 -291
  98. package/docs/parallel.md +0 -400
  99. package/docs/playwright.md +0 -632
  100. package/docs/plugins.md +0 -1247
  101. package/docs/puppeteer.md +0 -316
  102. package/docs/quickstart.md +0 -162
  103. package/docs/react.md +0 -70
  104. package/docs/reports.md +0 -392
  105. package/docs/secrets.md +0 -36
  106. package/docs/shadow.md +0 -68
  107. package/docs/shared/keys.mustache +0 -31
  108. package/docs/shared/react.mustache +0 -1
  109. package/docs/testcafe.md +0 -174
  110. package/docs/translation.md +0 -247
  111. package/docs/tutorial.md +0 -271
  112. package/docs/typescript.md +0 -180
  113. package/docs/ui.md +0 -59
  114. package/docs/videos.md +0 -28
  115. package/docs/visual.md +0 -202
  116. package/docs/vue.md +0 -143
  117. package/docs/webdriver.md +0 -701
  118. package/docs/wiki/Books-&-Posts.md +0 -27
  119. package/docs/wiki/Community-Helpers-&-Plugins.md +0 -53
  120. package/docs/wiki/Converting-Playwright-to-Istanbul-Coverage.md +0 -61
  121. package/docs/wiki/Examples.md +0 -145
  122. package/docs/wiki/Google-Summer-of-Code-(GSoC)-2020.md +0 -68
  123. package/docs/wiki/Home.md +0 -16
  124. package/docs/wiki/Migration-to-Appium-v2---CodeceptJS.md +0 -83
  125. package/docs/wiki/Release-Process.md +0 -24
  126. package/docs/wiki/Roadmap.md +0 -23
  127. package/docs/wiki/Tests.md +0 -1393
  128. package/docs/wiki/Upgrading-to-CodeceptJS-3.md +0 -153
  129. package/docs/wiki/Videos.md +0 -19
package/README.md CHANGED
@@ -313,10 +313,10 @@ Thanks all to those who are and will have contributing to this awesome project!
313
313
  <a href="https://github.com/tsuemura"><img src="https://avatars.githubusercontent.com/u/17092259?v=4" title="tsuemura" width="80" height="80"></a>
314
314
  <a href="https://github.com/EgorBodnar"><img src="https://avatars.githubusercontent.com/u/63167966?v=4" title="EgorBodnar" width="80" height="80"></a>
315
315
  <a href="https://github.com/VikalpP"><img src="https://avatars.githubusercontent.com/u/11846339?v=4" title="VikalpP" width="80" height="80"></a>
316
- <a href="https://github.com/BorisOsipov"><img src="https://avatars.githubusercontent.com/u/6514276?v=4" title="BorisOsipov" width="80" height="80"></a>
317
316
  <a href="https://github.com/elaichenkov"><img src="https://avatars.githubusercontent.com/u/29764053?v=4" title="elaichenkov" width="80" height="80"></a>
318
- <a href="https://github.com/nitschSB"><img src="https://avatars.githubusercontent.com/u/39341455?v=4" title="nitschSB" width="80" height="80"></a>
317
+ <a href="https://github.com/BorisOsipov"><img src="https://avatars.githubusercontent.com/u/6514276?v=4" title="BorisOsipov" width="80" height="80"></a>
319
318
  <a href="https://github.com/hubidu"><img src="https://avatars.githubusercontent.com/u/13134082?v=4" title="hubidu" width="80" height="80"></a>
319
+ <a href="https://github.com/nitschSB"><img src="https://avatars.githubusercontent.com/u/39341455?v=4" title="nitschSB" width="80" height="80"></a>
320
320
  <a href="https://github.com/jploskonka"><img src="https://avatars.githubusercontent.com/u/669483?v=4" title="jploskonka" width="80" height="80"></a>
321
321
  <a href="https://github.com/ngraf"><img src="https://avatars.githubusercontent.com/u/7094389?v=4" title="ngraf" width="80" height="80"></a>
322
322
  <a href="https://github.com/maojunxyz"><img src="https://avatars.githubusercontent.com/u/28778042?v=4" title="maojunxyz" width="80" height="80"></a>
package/bin/codecept.js CHANGED
@@ -272,5 +272,6 @@ program.on('command:*', (cmd) => {
272
272
 
273
273
  if (process.argv.length <= 2) {
274
274
  program.outputHelp();
275
+ } else {
276
+ program.parse(process.argv);
275
277
  }
276
- program.parse(process.argv);
@@ -0,0 +1,13 @@
1
+ Verifies that a certain request is not part of network traffic.
2
+
3
+ Examples:
4
+
5
+ ```js
6
+ I.dontSeeTraffic({ name: 'Unexpected API Call', url: 'https://api.example.com' });
7
+ I.dontSeeTraffic({ name: 'Unexpected API Call of "user" endpoint', url: /api.example.com.*user/ });
8
+ ```
9
+
10
+ @param {Object} opts - options when checking the traffic network.
11
+ @param {string} opts.name A name of that request. Can be any value. Only relevant to have a more meaningful error message in case of fail.
12
+ @param {string|RegExp} opts.url Expected URL of request in network traffic. Can be a string or a regular expression.
13
+ @return {void} automatically synchronized promise through #recorder
@@ -0,0 +1,5 @@
1
+ Resets all recorded network requests.
2
+
3
+ ```js
4
+ I.flushNetworkTraffics();
5
+ ```
@@ -0,0 +1,10 @@
1
+ Grab the recording network traffics
2
+
3
+ ```js
4
+ const traffics = await I.grabRecordedNetworkTraffics();
5
+ expect(traffics[0].url).to.equal('https://reqres.in/api/comments/1');
6
+ expect(traffics[0].response.status).to.equal(200);
7
+ expect(traffics[0].response.body).to.contain({ name: 'this was mocked' });
8
+ ```
9
+
10
+ @return { Array } recorded network traffics
@@ -0,0 +1,36 @@
1
+ Verifies that a certain request is part of network traffic.
2
+
3
+ ```js
4
+ // checking the request url contains certain query strings
5
+ I.amOnPage('https://openai.com/blog/chatgpt');
6
+ I.startRecordingTraffic();
7
+ await I.seeTraffic({
8
+ name: 'sentry event',
9
+ url: 'https://images.openai.com/blob/cf717bdb-0c8c-428a-b82b-3c3add87a600',
10
+ parameters: {
11
+ width: '1919',
12
+ height: '1138',
13
+ },
14
+ });
15
+ ```
16
+
17
+ ```js
18
+ // checking the request url contains certain post data
19
+ I.amOnPage('https://openai.com/blog/chatgpt');
20
+ I.startRecordingTraffic();
21
+ await I.seeTraffic({
22
+ name: 'event',
23
+ url: 'https://cloudflareinsights.com/cdn-cgi/rum',
24
+ requestPostData: {
25
+ st: 2,
26
+ },
27
+ });
28
+ ```
29
+
30
+ @param {Object} opts - options when checking the traffic network.
31
+ @param {string} opts.name A name of that request. Can be any value. Only relevant to have a more meaningful error message in case of fail.
32
+ @param {string} opts.url Expected URL of request in network traffic
33
+ @param {Object} [opts.parameters] Expected parameters of that request in network traffic
34
+ @param {Object} [opts.requestPostData] Expected that request contains post data in network traffic
35
+ @param {number} [opts.timeout] Timeout to wait for request in seconds. Default is 10 seconds.
36
+ @return {void} automatically synchronized promise through #recorder
@@ -0,0 +1,8 @@
1
+ Starts recording the network traffics.
2
+ This also resets recorded network requests.
3
+
4
+ ```js
5
+ I.startRecordingTraffic();
6
+ ```
7
+
8
+ @returns {void} automatically synchronized promise through #recorder
@@ -0,0 +1,8 @@
1
+ Starts recording of websocket messages.
2
+ This also resets recorded websocket messages.
3
+
4
+ ```js
5
+ await I.startRecordingWebSocketMessages();
6
+ ```
7
+
8
+ @returns {void} automatically synchronized promise through #recorder
@@ -0,0 +1,5 @@
1
+ Stops recording of network traffic. Recorded traffic is not flashed.
2
+
3
+ ```js
4
+ I.stopRecordingTraffic();
5
+ ```
@@ -0,0 +1,7 @@
1
+ Stops recording WS messages. Recorded WS messages is not flashed.
2
+
3
+ ```js
4
+ await I.stopRecordingWebSocketMessages();
5
+ ```
6
+
7
+ @returns {void} automatically synchronized promise through #recorder
@@ -0,0 +1,9 @@
1
+ Waits for the specified cookie in the cookies.
2
+
3
+ ```js
4
+ I.waitForCookie("token");
5
+ ```
6
+
7
+ @param {string} name expected cookie name.
8
+ @param {number} [sec=3] (optional, `3` by default) time in seconds to wait
9
+ @returns {void} automatically synchronized promise through #recorder
package/lib/actor.js CHANGED
@@ -13,15 +13,18 @@ const output = require('./output');
13
13
  */
14
14
  class Actor {
15
15
  /**
16
- * add print comment method`
16
+ * Print the comment on log. Also, adding a step in the `Test.steps` object
17
17
  * @param {string} msg
18
18
  * @param {string} color
19
19
  * @inner
20
20
  *
21
21
  * ⚠️ returns a promise which is synchronized internally by recorder
22
22
  */
23
- say(msg, color = 'cyan') {
24
- return recorder.add(`say ${msg}`, () => {
23
+ async say(msg, color = 'cyan') {
24
+ const step = new Step('say', 'say');
25
+ step.status = 'passed';
26
+ return recordStep(step, [msg]).then(() => {
27
+ // this is backward compatibility as this event may be used somewhere
25
28
  event.emit(event.step.comment, msg);
26
29
  output.say(msg, `${color}`);
27
30
  });
@@ -59,24 +59,39 @@ function printTests(files) {
59
59
 
60
60
  let numOfTests = 0;
61
61
  let numOfSuites = 0;
62
- const filteredSuites = [];
62
+ let outputString = '';
63
+ const filterBy = process.env.grep ? process.env.grep.toLowerCase() : undefined;
63
64
 
64
- for (const suite of mocha.suite.suites) {
65
- if (process.env.grep && suite.title.toLowerCase().includes(process.env.grep)) {
66
- filteredSuites.push(suite);
65
+ if (filterBy) {
66
+ for (const suite of mocha.suite.suites) {
67
+ const currentSuite = suite.title;
68
+ if (suite.title.toLowerCase().includes(filterBy)) {
69
+ outputString += `${colors.white.bold(suite.title)} -- ${output.styles.log(suite.file || '')} -- ${mocha.suite.suites.length} tests\n`;
70
+ numOfSuites++;
71
+ }
72
+
73
+ for (test of suite.tests) {
74
+ if (test.title.toLowerCase().includes(filterBy)) {
75
+ numOfTests++;
76
+ outputString += `${colors.white.bold(test.parent.title)} -- ${output.styles.log(test.parent.file || '')} -- ${mocha.suite.suites.length} tests\n`;
77
+ outputString += ` ${output.styles.scenario(figures.checkboxOff)} ${test.title}\n`;
78
+ }
79
+ }
67
80
  }
68
- }
69
- const displayedSuites = process.env.grep ? filteredSuites : mocha.suite.suites;
70
- for (const suite of displayedSuites) {
71
- output.print(`${colors.white.bold(suite.title)} -- ${output.styles.log(suite.file || '')} -- ${suite.tests.length} tests`);
72
- numOfSuites++;
73
-
74
- for (const test of suite.tests) {
75
- numOfTests++;
76
- output.print(` ${output.styles.scenario(figures.checkboxOff)} ${test.title}`);
81
+ numOfSuites = countSuites(outputString);
82
+ } else {
83
+ for (const suite of mocha.suite.suites) {
84
+ output.print(`${colors.white.bold(suite.title)} -- ${output.styles.log(suite.file || '')} -- ${mocha.suite.suites.length} tests`);
85
+ numOfSuites++;
86
+
87
+ for (test of suite.tests) {
88
+ numOfTests++;
89
+ output.print(` ${output.styles.scenario(figures.checkboxOff)} ${test.title}`);
90
+ }
77
91
  }
78
92
  }
79
93
 
94
+ output.print(removeDuplicates(outputString));
80
95
  output.print('');
81
96
  output.success(` Total: ${numOfSuites} suites | ${numOfTests} tests `);
82
97
  printFooter();
@@ -87,3 +102,19 @@ function printFooter() {
87
102
  output.print();
88
103
  output.print('--- DRY MODE: No tests were executed ---');
89
104
  }
105
+
106
+ function removeDuplicates(inputString) {
107
+ const array = inputString.split('\n');
108
+ const uniqueLines = [...new Set(array)];
109
+ const resultString = uniqueLines.join('\n');
110
+
111
+ return resultString;
112
+ }
113
+
114
+ function countSuites(inputString) {
115
+ const array = inputString.split('\n');
116
+
117
+ const uniqueLines = [...new Set(array)];
118
+ const res = uniqueLines.filter(item => item.includes('-- '));
119
+ return res.length;
120
+ }
@@ -2,6 +2,7 @@ let webdriverio;
2
2
 
3
3
  const fs = require('fs');
4
4
  const axios = require('axios').default;
5
+ const { v4: uuidv4 } = require('uuid');
5
6
 
6
7
  const Webdriver = require('./WebDriver');
7
8
  const AssertionFailedError = require('../assert/error');
@@ -1088,17 +1089,40 @@ class Appium extends Webdriver {
1088
1089
  * Appium: support Android and iOS
1089
1090
  */
1090
1091
  async performSwipe(from, to) {
1091
- await this.browser.touchPerform([{
1092
- action: 'press',
1093
- options: from,
1094
- }, {
1095
- action: 'wait',
1096
- options: { ms: 1000 },
1097
- }, {
1098
- action: 'moveTo',
1099
- options: to,
1100
- }, {
1101
- action: 'release',
1092
+ await this.browser.performActions([{
1093
+ id: uuidv4(),
1094
+ type: 'pointer',
1095
+ parameters: {
1096
+ pointerType: 'touch',
1097
+ },
1098
+ actions: [
1099
+ {
1100
+ duration: 0,
1101
+ x: from.x,
1102
+ y: from.y,
1103
+ type: 'pointerMove',
1104
+ origin: 'viewport',
1105
+ },
1106
+ {
1107
+ button: 1,
1108
+ type: 'pointerDown',
1109
+ },
1110
+ {
1111
+ duration: 200,
1112
+ type: 'pause',
1113
+ },
1114
+ {
1115
+ duration: 600,
1116
+ x: to.x,
1117
+ y: to.y,
1118
+ type: 'pointerMove',
1119
+ origin: 'viewport',
1120
+ },
1121
+ {
1122
+ button: 1,
1123
+ type: 'pointerUp',
1124
+ },
1125
+ ],
1102
1126
  }]);
1103
1127
  await this.browser.pause(1000);
1104
1128
  }
@@ -1128,7 +1152,7 @@ class Appium extends Webdriver {
1128
1152
  yoffset = 100;
1129
1153
  }
1130
1154
 
1131
- return this.swipe(locator, 0, yoffset, speed);
1155
+ return this.swipe(parseLocator.call(this, locator), 0, yoffset, speed);
1132
1156
  }
1133
1157
 
1134
1158
  /**
@@ -1,12 +1,15 @@
1
- const chai = require('chai');
2
1
  const output = require('../output');
3
2
 
4
- const { expect } = chai;
3
+ let expect;
5
4
 
6
- chai.use(require('chai-string'));
7
- // @ts-ignore
8
- chai.use(require('chai-exclude'));
9
- chai.use(require('chai-match-pattern'));
5
+ import('chai').then(chai => {
6
+ expect = chai.expect;
7
+ chai.use(require('chai-string'));
8
+ // @ts-ignore
9
+ chai.use(require('chai-exclude'));
10
+ chai.use(require('chai-match-pattern'));
11
+ chai.use(require('chai-json-schema'));
12
+ });
10
13
 
11
14
  /**
12
15
  * This helper allows performing assertions based on Chai.
@@ -179,7 +182,7 @@ class ExpectHelper {
179
182
  expectJsonSchema(targetData, jsonSchema, customErrorMsg = '') {
180
183
  // @ts-ignore
181
184
  output.step(`I expect "${JSON.stringify(targetData)}" to match this JSON schema "${JSON.stringify(jsonSchema)}"`);
182
- chai.use(require('chai-json-schema'));
185
+
183
186
  return expect(targetData, customErrorMsg).to.be.jsonSchema(jsonSchema);
184
187
  }
185
188
 
@@ -187,7 +190,7 @@ class ExpectHelper {
187
190
  * @param {*} targetData
188
191
  * @param {*} jsonSchema
189
192
  * @param {*} [customErrorMsg]
190
- * @param {*} ajvOptions Pass AJV options
193
+ * @param {*} [ajvOptions] Pass AJV options
191
194
  */
192
195
  expectJsonSchemaUsingAJV(
193
196
  targetData,
@@ -1,12 +1,13 @@
1
- const assert = require('assert');
2
- const chai = require('chai');
3
- const joi = require('joi');
4
- const chaiDeepMatch = require('chai-deep-match');
5
1
  const Helper = require('@codeceptjs/helper');
6
2
 
7
- chai.use(chaiDeepMatch);
3
+ let expect;
4
+
5
+ import('chai').then(chai => {
6
+ expect = chai.expect;
7
+ chai.use(require('chai-deep-match'));
8
+ });
8
9
 
9
- const { expect } = chai;
10
+ const joi = require('joi');
10
11
 
11
12
  /**
12
13
  * This helper allows performing assertions on JSON responses paired with following helpers:
@@ -91,7 +92,6 @@ class JSONResponse extends Helper {
91
92
  static _checkRequirements() {
92
93
  try {
93
94
  require('joi');
94
- require('chai');
95
95
  } catch (e) {
96
96
  return ['joi'];
97
97
  }
@@ -194,7 +194,7 @@ class JSONResponse extends Helper {
194
194
  fails++;
195
195
  }
196
196
  }
197
- assert.ok(fails < this.response.data.length, `No elements in array matched ${JSON.stringify(json)}`);
197
+ expect(fails < this.response.data.length, `No elements in array matched ${JSON.stringify(json)}`).to.be.true;
198
198
  } else {
199
199
  expect(this.response.data).to.deep.match(json);
200
200
  }
@@ -0,0 +1,221 @@
1
+ const { mock, settings } = require('pactum');
2
+
3
+ /**
4
+ * ## Configuration
5
+ *
6
+ * This helper should be configured in codecept.conf.(js|ts)
7
+ *
8
+ * @typedef MockServerConfig
9
+ * @type {object}
10
+ * @prop {number} [port=9393] - Mock server port
11
+ * @prop {string} [host="0.0.0.0"] - Mock server host
12
+ * @prop {object} [httpsOpts] - key & cert values are the paths to .key and .crt files
13
+ */
14
+ let config = {
15
+ port: 9393,
16
+ host: '0.0.0.0',
17
+ httpsOpts: {
18
+ key: '',
19
+ cert: '',
20
+ },
21
+ };
22
+
23
+ /**
24
+ * MockServer
25
+ *
26
+ * The MockServer Helper in CodeceptJS empowers you to mock any server or service via HTTP or HTTPS, making it an excellent tool for simulating REST endpoints and other HTTP-based APIs.
27
+ *
28
+ * <!-- configuration -->
29
+ *
30
+ * #### Examples
31
+ *
32
+ * You can seamlessly integrate MockServer with other helpers like REST or Playwright. Here's a configuration example inside the `codecept.conf.js` file:
33
+ *
34
+ * ```javascript
35
+ * {
36
+ * helpers: {
37
+ * REST: {...},
38
+ * MockServer: {
39
+ * // default mock server config
40
+ * port: 9393,
41
+ * host: '0.0.0.0',
42
+ * httpsOpts: {
43
+ * key: '',
44
+ * cert: '',
45
+ * },
46
+ * },
47
+ * }
48
+ * }
49
+ * ```
50
+ *
51
+ * #### Adding Interactions
52
+ *
53
+ * Interactions add behavior to the mock server. Use the `I.addInteractionToMockServer()` method to include interactions. It takes an interaction object as an argument, containing request and response details.
54
+ *
55
+ * ```javascript
56
+ * I.addInteractionToMockServer({
57
+ * request: {
58
+ * method: 'GET',
59
+ * path: '/api/hello'
60
+ * },
61
+ * response: {
62
+ * status: 200,
63
+ * body: {
64
+ * 'say': 'hello to mock server'
65
+ * }
66
+ * }
67
+ * });
68
+ * ```
69
+ *
70
+ * #### Request Matching
71
+ *
72
+ * When a real request is sent to the mock server, it matches the received request with the interactions. If a match is found, it returns the specified response; otherwise, a 404 status code is returned.
73
+ *
74
+ * - Strong match on HTTP Method, Path, Query Params & JSON body.
75
+ * - Loose match on Headers.
76
+ *
77
+ * ##### Strong Match on Query Params
78
+ *
79
+ * You can send different responses based on query parameters:
80
+ *
81
+ * ```javascript
82
+ * I.addInteractionToMockServer({
83
+ * request: {
84
+ * method: 'GET',
85
+ * path: '/api/users',
86
+ * queryParams: {
87
+ * id: 1
88
+ * }
89
+ * },
90
+ * response: {
91
+ * status: 200,
92
+ * body: 'user 1'
93
+ * }
94
+ * });
95
+ *
96
+ * I.addInteractionToMockServer({
97
+ * request: {
98
+ * method: 'GET',
99
+ * path: '/api/users',
100
+ * queryParams: {
101
+ * id: 2
102
+ * }
103
+ * },
104
+ * response: {
105
+ * status: 200,
106
+ * body: 'user 2'
107
+ * }
108
+ * });
109
+ * ```
110
+ *
111
+ * - GET to `/api/users?id=1` will return 'user 1'.
112
+ * - GET to `/api/users?id=2` will return 'user 2'.
113
+ * - For all other requests, it returns a 404 status code.
114
+ *
115
+ * ##### Loose Match on Body
116
+ *
117
+ * When `strict` is set to false, it performs a loose match on query params and response body:
118
+ *
119
+ * ```javascript
120
+ * I.addInteractionToMockServer({
121
+ * strict: false,
122
+ * request: {
123
+ * method: 'POST',
124
+ * path: '/api/users',
125
+ * body: {
126
+ * name: 'john'
127
+ * }
128
+ * },
129
+ * response: {
130
+ * status: 200
131
+ * }
132
+ * });
133
+ * ```
134
+ *
135
+ * - POST to `/api/users` with the body containing `name` as 'john' will return a 200 status code.
136
+ * - POST to `/api/users` without the `name` property in the body will return a 404 status code.
137
+ *
138
+ * Happy testing with MockServer in CodeceptJS! 🚀
139
+ *
140
+ * ## Methods
141
+ */
142
+ class MockServer {
143
+ constructor(passedConfig) {
144
+ settings.setLogLevel('SILENT');
145
+ config = { ...passedConfig };
146
+ if (global.debugMode) {
147
+ settings.setLogLevel('VERBOSE');
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Start the mock server
153
+ * @param {number} [port] start the mock server with given port
154
+ *
155
+ * @returns void
156
+ */
157
+ async startMockServer(port) {
158
+ const _config = { ...config };
159
+ if (port) _config.port = port;
160
+ await mock.setDefaults(_config);
161
+ await mock.start();
162
+ }
163
+
164
+ /**
165
+ * Stop the mock server
166
+ *
167
+ * @returns void
168
+ *
169
+ */
170
+ async stopMockServer() {
171
+ await mock.stop();
172
+ }
173
+
174
+ /**
175
+ * An interaction adds behavior to the mock server
176
+ *
177
+ *
178
+ * ```js
179
+ * I.addInteractionToMockServer({
180
+ * request: {
181
+ * method: 'GET',
182
+ * path: '/api/hello'
183
+ * },
184
+ * response: {
185
+ * status: 200,
186
+ * body: {
187
+ * 'say': 'hello to mock server'
188
+ * }
189
+ * }
190
+ * });
191
+ * ```
192
+ * ```js
193
+ * // with query params
194
+ * I.addInteractionToMockServer({
195
+ * request: {
196
+ * method: 'GET',
197
+ * path: '/api/hello',
198
+ * queryParams: {
199
+ * id: 2
200
+ * }
201
+ * },
202
+ * response: {
203
+ * status: 200,
204
+ * body: {
205
+ * 'say': 'hello to mock server'
206
+ * }
207
+ * }
208
+ * });
209
+ * ```
210
+ *
211
+ * @param {CodeceptJS.MockInteraction|object} interaction add behavior to the mock server
212
+ *
213
+ * @returns void
214
+ *
215
+ */
216
+ async addInteractionToMockServer(interaction) {
217
+ await mock.addInteraction(interaction);
218
+ }
219
+ }
220
+
221
+ module.exports = MockServer;