testit-adapter-jest 1.1.7 → 2.0.1

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
@@ -10,13 +10,6 @@ npm install testit-adapter-jest
10
10
 
11
11
  ## Usage
12
12
 
13
- ### API client
14
-
15
- To use adapter you need to install `testit-api-client`:
16
- ```
17
- npm install testit-api-client
18
- ```
19
-
20
13
  ### Configuration
21
14
 
22
15
  | Description | Property | Environment variable | CLI argument |
@@ -85,20 +78,21 @@ You can also specify options via cli arguments `jest --testEnvironment testit-ad
85
78
  Methods can be used to specify information about autotest.
86
79
 
87
80
  Description of metadata methods:
88
- - `testit.workItemIds` - linking an autotest to a test case
89
- - `testit.displayName` - name of the autotest in the Test IT system (can be replaced with documentation strings)
90
- - `testit.externalId` - ID of the autotest within the project in the Test IT System
91
- - `testit.title` - title in the autotest card
92
- - `testit.description` - description in the autotest card
93
- - `testit.labels` - tags in the work item
94
- - `testit.link` - links in the autotest card
95
- - `testit.nameSpace` - directory in the TMS system (default - directory's name of test)
96
- - `testit.className` - subdirectory in the TMS system (default - file's name of test)
81
+ - `testit.workItemIds` - a method that links autotests with manual tests. Receives the array of manual tests' IDs
82
+ - `testit.displayName` - internal autotest name (used in Test IT)
83
+ - `testit.externalId` - unique internal autotest ID (used in Test IT)
84
+ - `testit.title` - autotest name specified in the autotest card. If not specified, the name from the displayName method is used
85
+ - `testit.description` - autotest description specified in the autotest card
86
+ - `testit.labels` - tags listed in the autotest card
87
+ - `testit.link` - links listed in the autotest card
88
+ - `testit.namespace` - directory in the TMS system (default - directory's name of test)
89
+ - `testit.classname` - subdirectory in the TMS system (default - file's name of test)
97
90
 
98
91
  Description of methods:
99
92
  - `testit.addLinks` - links in the autotest result
100
93
  - `testit.addAttachments` - uploading files in the autotest result
101
94
  - `testit.addMessage` - information about autotest in the autotest result
95
+ - `testit.step` - add step of autotest
102
96
 
103
97
  ### Examples
104
98
 
@@ -1,3 +1,3 @@
1
- import { Config } from '@jest/reporters';
1
+ import { Config } from "@jest/reporters";
2
2
  declare const _default: (globalConfig: Config.GlobalConfig, projectConfig: Config.ProjectConfig) => Promise<void>;
3
3
  export default _default;
@@ -1,35 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const testClient_1 = require("./testClient");
4
- const utils_1 = require("./utils");
3
+ const testit_js_commons_1 = require("testit-js-commons");
5
4
  exports.default = async (globalConfig, projectConfig) => {
6
- const adapterMode = projectConfig.testEnvironmentOptions?.adapterMode ?? 0;
7
- const automaticCreationTestCases = projectConfig.testEnvironmentOptions?.automaticCreationTestCases ?? false;
8
- let testRunId;
9
- try {
10
- switch (adapterMode) {
11
- case 0:
12
- case 1: {
13
- testRunId = projectConfig.testEnvironmentOptions?.testRunId;
14
- if (!testRunId) {
15
- throw new Error('testRunId is required when mode is 1');
16
- }
17
- globalThis.testClient = new testClient_1.TestClient(projectConfig.testEnvironmentOptions);
18
- break;
19
- }
20
- case 2: {
21
- globalThis.testClient = new testClient_1.TestClient(projectConfig.testEnvironmentOptions);
22
- testRunId = await globalThis.testClient.createTestRun();
23
- break;
24
- }
25
- default:
26
- throw new Error(`Unknown adapter mode ${adapterMode}`);
27
- }
28
- }
29
- catch (err) {
30
- console.error('Failed to setup', (0, utils_1.formatError)(err));
31
- process.exit(1);
32
- }
33
- projectConfig.globals['testRunId'] = testRunId;
34
- projectConfig.globals['automaticCreationTestCases'] = automaticCreationTestCases;
5
+ const config = new testit_js_commons_1.ConfigComposer().compose(projectConfig.testEnvironmentOptions);
6
+ const client = new testit_js_commons_1.Client(config);
7
+ const strategy = testit_js_commons_1.StrategyFactory.create(client, config);
8
+ await strategy.setup();
9
+ const testRunId = await strategy.testRunId;
10
+ globalThis.client = client;
11
+ projectConfig.globals["testRunId"] = testRunId;
35
12
  };
@@ -1,16 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const utils_1 = require("./utils");
4
3
  exports.default = async (globalConfig, projectConfig) => {
5
4
  const testRunId = projectConfig.globals['testRunId'];
6
5
  if (!testRunId) {
7
- console.error('Looks like globalSetup was not called');
8
- return;
6
+ return console.error('Looks like globalSetup was not called');
9
7
  }
10
8
  try {
11
- await globalThis.testClient.completeTestRun();
9
+ await globalThis.client.testRuns.completeTestRun(testRunId);
12
10
  }
13
11
  catch (err) {
14
- console.error('Failed to complete test run', (0, utils_1.formatError)(err));
12
+ console.error('Failed to complete test run');
15
13
  }
16
14
  };
@@ -1,41 +1,41 @@
1
1
  /// <reference types="node" />
2
- import type { EnvironmentContext, JestEnvironmentConfig } from '@jest/environment';
3
- import { Event, State } from 'jest-circus';
4
- import NodeEnvironment from 'jest-environment-node';
5
- import { LinkPost } from 'testit-api-client';
2
+ import type { EnvironmentContext, JestEnvironmentConfig } from "@jest/environment";
3
+ import { Event } from "jest-circus";
4
+ import NodeEnvironment from "jest-environment-node";
5
+ import { Link } from "testit-js-commons";
6
6
  export default class TestItEnvironment extends NodeEnvironment {
7
7
  private autotestData;
8
8
  private currentStepData;
9
- private testClient;
10
9
  private beforeAllSteps;
11
10
  private afterAllSteps;
12
11
  private currentType;
13
12
  private autotestResults;
14
13
  private autotests;
15
- private testPath;
14
+ private readonly testPath;
16
15
  private attachmentsQueue;
17
- private automaticCreationTestCases;
18
- constructor(config: JestEnvironmentConfig, context: EnvironmentContext);
16
+ private readonly client;
17
+ private readonly additions;
18
+ constructor(jestConfig: JestEnvironmentConfig, jestContext: EnvironmentContext);
19
19
  setup(): Promise<void>;
20
20
  teardown(): Promise<void>;
21
21
  getVmContext(): import("vm").Context | null;
22
22
  exportConditions(): string[];
23
- handleTestEvent(event: Event, state: State): Promise<void>;
23
+ handleTestEvent(event: Event): Promise<void>;
24
24
  startHookCapture(hook: Extract<Event, {
25
- name: 'hook_start';
26
- }>['hook']): void;
25
+ name: "hook_start";
26
+ }>["hook"]): void;
27
27
  finishHookCapture(hook: Extract<Event, {
28
- name: 'hook_start';
29
- }>['hook']): void;
28
+ name: "hook_start";
29
+ }>["hook"]): void;
30
30
  startTestCapture(test: Extract<Event, {
31
- name: 'test_fn_start';
32
- }>['test']): void;
31
+ name: "test_fn_start";
32
+ }>["test"]): void;
33
33
  finishTestCapture(test: Extract<Event, {
34
- name: 'test_fn_success';
35
- }>['test']): void;
34
+ name: "test_fn_success";
35
+ }>["test"]): void;
36
36
  saveResult(test: Extract<Event, {
37
- name: 'test_done';
38
- }>['test']): void;
37
+ name: "test_done";
38
+ }>["test"]): Promise<void>;
39
39
  loadResults(): Promise<void>;
40
40
  resetTest(): void;
41
41
  resetStep(): void;
@@ -45,9 +45,7 @@ export default class TestItEnvironment extends NodeEnvironment {
45
45
  setDescription(description: string): void;
46
46
  addAttachments(attachment: string, name?: string): void;
47
47
  addAttachments(attachments: string[]): void;
48
- addLinks(links: LinkPost[]): void;
49
- addMessage(message: string): void;
50
- setAutotestLinks(links: LinkPost[]): void;
48
+ setLinks(links: Link[]): void;
51
49
  setLabels(labels: string[]): void;
52
50
  setWorkItems(workItems: string[]): void;
53
51
  setParams(params: any): void;
@@ -4,30 +4,28 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const jest_environment_node_1 = __importDefault(require("jest-environment-node"));
7
- const debug_1 = require("./debug");
8
- const mappers_1 = require("./mappers");
9
- const testClient_1 = require("./testClient");
7
+ const testit_js_commons_1 = require("testit-js-commons");
8
+ const debug_1 = require("debug");
10
9
  const utils_1 = require("./utils");
11
- const log = debug_1.debug.extend('environment');
12
- const emptyTitle = '__EMPTY__';
10
+ const log = (0, debug_1.debug)("tms").extend("environment");
13
11
  const emptyAutotestData = () => ({
14
- name: emptyTitle,
12
+ externalId: "",
13
+ name: "",
15
14
  steps: [],
16
15
  afterEach: [],
16
+ testSteps: [],
17
17
  beforeEach: [],
18
18
  attachments: [],
19
19
  links: [],
20
- runtimeLinks: [],
21
20
  labels: [],
22
- workItems: [],
23
21
  });
24
22
  const emptyStepData = () => ({
25
- title: emptyTitle,
23
+ title: "",
26
24
  attachments: [],
27
25
  });
28
26
  class TestItEnvironment extends jest_environment_node_1.default {
29
- constructor(config, context) {
30
- super(config, context);
27
+ constructor(jestConfig, jestContext) {
28
+ super(jestConfig, jestContext);
31
29
  this.autotestData = emptyAutotestData();
32
30
  this.currentStepData = emptyStepData();
33
31
  this.beforeAllSteps = [];
@@ -35,28 +33,21 @@ class TestItEnvironment extends jest_environment_node_1.default {
35
33
  this.autotestResults = [];
36
34
  this.autotests = [];
37
35
  this.attachmentsQueue = [];
38
- const testRunId = config.projectConfig.globals['testRunId'];
39
- const automaticCreationTestCases = config.projectConfig.globals['automaticCreationTestCases'];
40
- if (!testRunId || typeof testRunId !== 'string') {
41
- throw new Error('Looks like globalSetup was not called');
36
+ const config = new testit_js_commons_1.ConfigComposer().compose(jestConfig.projectConfig.testEnvironmentOptions);
37
+ const testRunId = jestConfig.projectConfig.globals["testRunId"];
38
+ if (!testRunId || typeof testRunId !== "string") {
39
+ throw new Error("Looks like globalSetup was not called");
42
40
  }
43
- if (!automaticCreationTestCases || typeof automaticCreationTestCases !== 'boolean') {
44
- throw new Error('Looks like globalSetup was not called');
45
- }
46
- this.automaticCreationTestCases = automaticCreationTestCases;
47
- this.testClient = new testClient_1.TestClient({
48
- ...config.projectConfig.testEnvironmentOptions,
49
- testRunId,
50
- });
51
- this.testPath = (0, utils_1.excludePath)(context.testPath, config.globalConfig.rootDir);
41
+ this.client = new testit_js_commons_1.Client({ ...config, testRunId });
42
+ this.additions = new testit_js_commons_1.Additions(this.client);
43
+ this.testPath = (0, utils_1.excludePath)(jestContext.testPath, jestConfig.globalConfig.rootDir);
52
44
  }
53
45
  async setup() {
54
46
  await super.setup();
55
- (0, utils_1.createTempDir)();
56
47
  this.global.testit = {
57
48
  externalId: this.setExternalId.bind(this),
58
49
  displayName: this.setDisplayName.bind(this),
59
- links: this.setAutotestLinks.bind(this),
50
+ links: this.setLinks.bind(this),
60
51
  labels: this.setLabels.bind(this),
61
52
  workItemIds: this.setWorkItems.bind(this),
62
53
  params: this.setParams.bind(this),
@@ -64,15 +55,14 @@ class TestItEnvironment extends jest_environment_node_1.default {
64
55
  title: this.setTitle.bind(this),
65
56
  description: this.setDescription.bind(this),
66
57
  addAttachments: this.addAttachments.bind(this),
67
- addLinks: this.addLinks.bind(this),
68
- addMessage: this.addMessage.bind(this),
69
- nameSpace: this.setNameSpace.bind(this),
70
- className: this.setClassName.bind(this),
58
+ addLinks: this.additions.addLinks.bind(this.additions),
59
+ addMessage: this.additions.addMessage.bind(this.additions),
60
+ namespace: this.setNameSpace.bind(this),
61
+ classname: this.setClassName.bind(this),
71
62
  };
72
63
  }
73
64
  async teardown() {
74
65
  await super.teardown();
75
- (0, utils_1.removeTempDir)();
76
66
  }
77
67
  getVmContext() {
78
68
  return super.getVmContext();
@@ -80,62 +70,66 @@ class TestItEnvironment extends jest_environment_node_1.default {
80
70
  exportConditions() {
81
71
  return super.exportConditions();
82
72
  }
83
- async handleTestEvent(event, state) {
73
+ async handleTestEvent(event) {
84
74
  switch (event.name) {
85
- case 'hook_start': {
75
+ case "hook_start": {
86
76
  this.startHookCapture(event.hook);
87
77
  break;
88
78
  }
89
- case 'hook_success':
90
- case 'hook_failure': {
79
+ case "hook_success":
80
+ case "hook_failure": {
91
81
  this.finishHookCapture(event.hook);
92
82
  break;
93
83
  }
94
- case 'test_fn_start': {
84
+ case "test_fn_start": {
95
85
  this.startTestCapture(event.test);
96
86
  break;
97
87
  }
98
- case 'test_fn_success':
99
- case 'test_fn_failure': {
88
+ case "test_fn_success":
89
+ case "test_fn_failure": {
100
90
  this.finishTestCapture(event.test);
101
91
  break;
102
92
  }
103
- case 'test_done': {
104
- this.saveResult(event.test);
93
+ case "test_done": {
94
+ await this.saveResult(event.test);
105
95
  break;
106
96
  }
107
- case 'test_skip': {
97
+ case "test_skip": {
108
98
  this.resetTest();
109
99
  break;
110
100
  }
111
- case 'run_finish': {
101
+ case "run_finish": {
112
102
  await this.loadResults();
113
103
  break;
114
104
  }
115
105
  }
116
106
  }
117
107
  startHookCapture(hook) {
118
- log('Starting hook capture %s', hook.type);
108
+ log("Starting hook capture %s", hook.type);
119
109
  this.currentType = hook.type;
120
110
  // Use the hook type as the step name
121
111
  this.currentStepData.title = hook.type;
112
+ this.currentStepData.startedOn = new Date();
122
113
  }
123
114
  finishHookCapture(hook) {
124
- log('Finishing hook capture %s', hook.type);
115
+ log("Finishing hook capture %s", hook.type);
116
+ this.currentStepData.completedOn = new Date();
117
+ this.currentStepData.duration =
118
+ this.currentStepData.completedOn.getTime() - this.currentStepData.startedOn.getTime();
125
119
  switch (hook.type) {
126
- case 'beforeAll': {
120
+ case "beforeAll": {
127
121
  this.beforeAllSteps.push(this.currentStepData);
128
122
  break;
129
123
  }
130
- case 'afterAll': {
124
+ case "afterAll": {
131
125
  this.afterAllSteps.push(this.currentStepData);
132
126
  break;
133
127
  }
134
- case 'beforeEach': {
128
+ case "beforeEach": {
135
129
  this.autotestData.beforeEach.push(this.currentStepData);
136
130
  break;
137
131
  }
138
- case 'afterEach': {
132
+ case "afterEach": {
139
133
  this.autotestData.afterEach.push(this.currentStepData);
140
134
  break;
141
135
  }
@@ -143,223 +137,174 @@ class TestItEnvironment extends jest_environment_node_1.default {
143
137
  this.resetStep();
144
138
  }
145
139
  startTestCapture(test) {
146
- log('Starting test capture %s', test.name);
147
- this.currentType = 'test';
140
+ log("Starting test capture %s", test.name);
141
+ this.currentType = "test";
148
142
  this.setDisplayName(test.name);
143
+ this.setExternalId(this.generateExternalId(test.name));
149
144
  }
150
145
  finishTestCapture(test) {
151
- log('Finishing test capture %s', test.name);
152
- if (this.currentStepData.title !== emptyTitle) {
153
- this.autotestData.steps.push(this.currentStepData);
146
+ log("Finishing test capture %s", test.name);
147
+ if (this.currentStepData.title !== "") {
148
+ this.autotestData.testSteps.push(this.currentStepData);
154
149
  this.resetStep();
155
150
  }
156
151
  this.currentType = undefined;
157
152
  }
158
- saveResult(test) {
159
- log('Saving result for %s', test.name);
160
- const errorMessage = test.errors.length > 0
161
- ? test.errors.map((err) => err[0]?.message).join('\n')
162
- : undefined;
163
- const errorTraces = test.errors.length > 0
164
- ? test.errors.map((err) => err[0]?.stack).join('\n')
165
- : undefined;
153
+ async saveResult(test) {
154
+ log("Saving result for %s", test.name);
155
+ await Promise.all(this.attachmentsQueue);
156
+ const errorMessage = test.errors.length > 0 ? test.errors.map((err) => err[0]?.message).join("\n") : undefined;
157
+ const errorTraces = test.errors.length > 0 ? test.errors.map((err) => err[0]?.stack).join("\n") : undefined;
166
158
  const result = {
167
- isFailed: test.errors.length > 0,
168
- startedAt: test.startedAt ?? undefined,
159
+ autoTestExternalId: this.autotestData.externalId,
160
+ outcome: test.errors.length > 0 ? "Failed" : "Passed",
161
+ startedOn: test.startedAt ? new Date(test.startedAt) : undefined,
169
162
  duration: test.duration ?? undefined,
170
- finishedAt: test.startedAt && (0, utils_1.isDefined)(test.duration)
171
- ? test.startedAt + test.duration
172
- : undefined,
173
- message: errorMessage,
174
- trace: errorTraces,
163
+ traces: errorTraces,
164
+ attachments: this.additions.attachments,
165
+ message: this.additions.messages.join("\n").concat(errorMessage ?? ""),
166
+ links: this.additions.links,
175
167
  };
176
168
  this.autotests.push(this.autotestData);
177
169
  this.autotestResults.push(result);
178
170
  this.resetTest();
179
171
  }
180
172
  async loadResults() {
181
- log('Waiting for attachments to be uploaded');
173
+ log("Waiting for attachments to be uploaded");
182
174
  await Promise.all(this.attachmentsQueue);
183
175
  const results = [];
184
176
  for (let i = 0; i < this.autotests.length; i++) {
185
177
  const autotest = this.autotests[i];
186
178
  const result = this.autotestResults[i];
187
- log('Mapping autotest %s', autotest.name);
179
+ log("Mapping autotest %s", autotest.name);
188
180
  const setupSteps = this.beforeAllSteps.concat(autotest.beforeEach);
189
181
  const teardownSteps = autotest.afterEach.concat(this.afterAllSteps);
190
182
  const autotestPost = {
191
- projectId: this.testClient.projectId,
192
- externalId: autotest.externalId ?? this.generateExternalId(autotest.name),
183
+ externalId: autotest.externalId,
193
184
  title: autotest.title,
194
185
  name: autotest.name,
195
186
  description: autotest.description,
196
- namespace: autotest.namespace ?? (0, utils_1.getDir)(this.testPath),
197
- classname: autotest.classname ?? (0, utils_1.getFileName)(this.testPath),
198
- setup: setupSteps.map(mappers_1.mapStep),
199
- steps: autotest.steps.map(mappers_1.mapStep),
200
- teardown: teardownSteps.map(mappers_1.mapStep),
201
187
  links: autotest.links,
202
- labels: autotest.labels.map((label) => ({ name: label })),
203
- shouldCreateWorkItem: this.automaticCreationTestCases,
188
+ labels: autotest.labels,
189
+ namespace: autotest.namespace ?? testit_js_commons_1.Utils.getDir(this.testPath),
190
+ classname: autotest.classname ?? testit_js_commons_1.Utils.getFileName(this.testPath),
191
+ setup: setupSteps,
192
+ steps: autotest.testSteps,
193
+ teardown: teardownSteps,
194
+ shouldCreateWorkItem: this.client.getConfig().automaticCreationTestCases,
204
195
  };
205
- if (!result.isFailed) {
206
- await this.testClient.loadPassedAutotest(autotestPost);
207
- }
208
- else {
209
- await this.testClient.loadAutotest(autotestPost);
210
- }
211
- if (autotest.workItems.length > 0) {
212
- const id = await this.testClient.getAutotestId(autotestPost.externalId);
213
- try {
214
- await Promise.all(autotest.workItems.map((workItem) => {
215
- return this.testClient.linkWorkItem(id, workItem);
216
- }));
217
- }
218
- catch (err) {
219
- console.error('Failed to link work items', (0, utils_1.formatError)(err));
220
- }
221
- }
222
- const messages = [];
223
- if (autotest.message) {
224
- messages.push(autotest.message);
225
- }
226
- if (result.message) {
227
- messages.push(result.message);
196
+ await this.client.autoTests.loadAutotest(autotestPost, result.outcome === "Passed");
197
+ if (Array.isArray(autotest.workItemIds) && autotest.workItemIds.length > 0) {
198
+ await this.client.autoTests
199
+ .linkToWorkItems(autotest.externalId, autotest.workItemIds)
200
+ .catch((err) => console.error("Failed to link work items.", err));
228
201
  }
229
202
  results.push({
230
- autotestExternalId: autotestPost.externalId,
231
- configurationId: this.testClient.configurationId,
232
- outcome: result.isFailed ? 'Failed' : 'Passed',
233
- startedOn: result.startedAt ? (0, mappers_1.mapDate)(result.startedAt) : undefined,
234
- duration: result.duration ? result.duration : undefined,
235
- completedOn: result.finishedAt ? (0, mappers_1.mapDate)(result.finishedAt) : undefined,
236
- attachments: (0, mappers_1.mapAttachments)(autotest.attachments),
237
- message: messages.length > 0 ? messages.join('\n') : undefined,
238
- traces: result.trace,
239
- stepResults: autotest.steps.map(mappers_1.mapStepResult),
240
- setupResults: setupSteps.map(mappers_1.mapStepResult),
241
- teardownResults: teardownSteps.map(mappers_1.mapStepResult),
242
- links: autotest.runtimeLinks,
243
- parameters: autotest.params !== undefined
244
- ? (0, mappers_1.mapParams)(autotest.params)
245
- : undefined,
203
+ autoTestExternalId: autotestPost.externalId,
204
+ outcome: result.outcome,
205
+ startedOn: result.startedOn,
206
+ duration: result.duration,
207
+ attachments: result.attachments,
208
+ message: result.message,
209
+ links: result.links,
210
+ stepResults: autotest.testSteps,
211
+ traces: result.traces,
212
+ setupResults: setupSteps,
213
+ teardownResults: teardownSteps,
214
+ parameters: autotest.parameters !== undefined ? (0, utils_1.mapParams)(autotest.parameters) : undefined,
246
215
  });
247
216
  }
248
- log('Loading results');
249
- await this.testClient.loadAutotestResults(results);
217
+ log("Loading results");
218
+ const testRunId = this.client.getConfig().testRunId;
219
+ await this.client.testRuns.loadAutotests(testRunId, results);
250
220
  }
251
221
  resetTest() {
252
222
  this.autotestData = emptyAutotestData();
223
+ this.additions.clear();
253
224
  this.currentType = undefined;
254
225
  }
255
226
  resetStep() {
256
227
  this.currentStepData = emptyStepData();
257
228
  }
258
229
  setExternalId(id) {
259
- log('Setting external id to %s', id);
230
+ log("Setting external id to %s", id);
260
231
  this.autotestData.externalId = id;
261
232
  }
262
233
  setDisplayName(name) {
263
- log('Setting display name to %s', name);
234
+ log("Setting display name to %s", name);
264
235
  this.autotestData.name = name;
265
236
  }
266
237
  setTitle(title) {
267
- if (this.currentType === 'test') {
268
- log('Setting autotest title to %s', title);
238
+ if (this.currentType === "test") {
239
+ log("Setting autotest title to %s", title);
269
240
  this.autotestData.title = title;
270
241
  }
271
242
  else {
272
- log('Setting step title to %s', title);
243
+ log("Setting step title to %s", title);
273
244
  this.currentStepData.title = title;
274
245
  }
275
246
  }
276
247
  setDescription(description) {
277
- if (this.currentType === 'test') {
278
- log('Setting autotest description to %s', description);
248
+ if (this.currentType === "test") {
249
+ log("Setting autotest description to %s", description);
279
250
  this.autotestData.description = description;
280
251
  }
281
252
  else {
282
- log('Setting step description to %s', description);
253
+ log("Setting step description to %s", description);
283
254
  this.currentStepData.description = description;
284
255
  }
285
256
  }
286
257
  addAttachments(attachments, name) {
287
258
  const autotest = this.autotestData;
288
259
  const step = this.currentStepData;
289
- let target;
290
- if (this.currentType === 'test') {
291
- log('Adding attachments to %s', autotest.name);
292
- target = autotest.attachments;
293
- }
294
- else {
295
- log('Adding attachments to %s', step.title);
296
- target = step.attachments;
297
- }
298
- let files;
299
- if (Array.isArray(attachments)) {
300
- files = attachments;
301
- }
302
- else {
303
- if (!name) {
304
- name = (0, utils_1.generateFileName)();
305
- }
306
- const path = (0, utils_1.createTempFile)(name, attachments);
307
- files = [path];
308
- }
309
- const promise = this.testClient.uploadAttachments(files).then((ids) => {
310
- target.push(...ids);
260
+ const currentType = this.currentType;
261
+ // @ts-ignore
262
+ const promise = this.additions.addAttachments(attachments, name).then((ids) => {
263
+ currentType === "test" ? autotest.attachments.push(...ids) : step.attachments?.push(...ids);
311
264
  });
312
265
  this.attachmentsQueue.push(promise);
313
266
  return promise;
314
267
  }
315
- addLinks(links) {
316
- log('Adding links to %s', this.autotestData.name);
317
- this.autotestData.runtimeLinks.push(...links);
318
- }
319
- addMessage(message) {
320
- log('Adding message to %s', this.autotestData.name);
321
- this.autotestData.message = message;
322
- }
323
- setAutotestLinks(links) {
324
- log('Setting autotest links to %s', this.autotestData.name);
268
+ setLinks(links) {
269
+ log("Setting autotest links to %s", this.autotestData.name);
325
270
  this.autotestData.links = links;
326
271
  }
327
272
  setLabels(labels) {
328
- log('Setting labels to %s', this.autotestData.name);
329
- this.autotestData.labels = labels;
273
+ log("Setting labels to %s", this.autotestData.name);
274
+ this.autotestData.labels = labels.map((label) => ({ name: label }));
330
275
  }
331
276
  setWorkItems(workItems) {
332
- log('Setting work items to %s', this.autotestData.name);
333
- this.autotestData.workItems = workItems;
277
+ log("Setting work items to %s", this.autotestData.name);
278
+ this.autotestData.workItemIds = workItems;
334
279
  }
335
280
  setParams(params) {
336
- log('Setting params to %s', this.autotestData.name);
337
- this.autotestData.params = params;
281
+ log("Setting params to %s", this.autotestData.name);
282
+ this.autotestData.parameters = params;
338
283
  }
339
284
  setNameSpace(nameSpace) {
340
- log('Setting nameSpace to %s', nameSpace);
285
+ log("Setting nameSpace to %s", nameSpace);
341
286
  this.autotestData.namespace = nameSpace;
342
287
  }
343
288
  setClassName(className) {
344
- log('Setting className to %s', className);
289
+ log("Setting className to %s", className);
345
290
  this.autotestData.classname = className;
346
291
  }
347
292
  startStep(name, description) {
348
- log('Starting step %s', name);
349
- if (this.currentType !== 'test' && this.currentType !== 'step') {
350
- log('Step can only be started in test');
293
+ log("Starting step %s", name);
294
+ if (this.currentType !== "test" && this.currentType !== "step") {
295
+ log("Step can only be started in test");
351
296
  return;
352
297
  }
353
- if (this.currentType === 'step') {
354
- this.autotestData.steps.push(this.currentStepData);
298
+ if (this.currentType === "step") {
299
+ this.autotestData.testSteps.push(this.currentStepData);
355
300
  this.resetStep();
356
301
  }
357
- this.currentType = 'step';
302
+ this.currentType = "step";
358
303
  this.currentStepData.title = name;
359
304
  this.currentStepData.description = description;
360
305
  }
361
306
  generateExternalId(testName) {
362
- return (0, utils_1.getHash)(JSON.stringify({
307
+ return testit_js_commons_1.Utils.getHash(JSON.stringify({
363
308
  path: this.testPath,
364
309
  name: testName,
365
310
  }));
package/dist/types.d.ts CHANGED
@@ -1,32 +1,9 @@
1
- import { LinkPost } from 'testit-api-client';
2
- export type StepData = {
3
- title: string;
4
- description?: string;
5
- attachments: string[];
6
- };
7
- export type AutotestData = {
8
- name: string;
9
- title?: string;
10
- description?: string;
11
- externalId?: string;
12
- namespace?: string;
13
- classname?: string;
14
- attachments: string[];
15
- beforeEach: StepData[];
16
- steps: StepData[];
17
- afterEach: StepData[];
18
- links: LinkPost[];
19
- runtimeLinks: LinkPost[];
20
- message?: string;
21
- labels: string[];
22
- workItems: string[];
23
- params?: any;
24
- };
25
- export type AutotestResult = {
26
- startedAt?: number;
27
- duration?: number;
28
- finishedAt?: number;
29
- isFailed: boolean;
30
- message?: string;
31
- trace?: string;
32
- };
1
+ import { AutotestPost, Attachment, Step } from "testit-js-commons";
2
+ export interface AutotestData extends AutotestPost {
3
+ parameters?: any;
4
+ attachments: Array<Attachment>;
5
+ beforeEach: Step[];
6
+ afterEach: Step[];
7
+ testSteps: Step[];
8
+ }
9
+ export type Parameters = Record<string, string>;
package/dist/utils.d.ts CHANGED
@@ -1,13 +1,3 @@
1
- export declare function isDefined<T>(value: T | undefined | null): value is T;
2
- export declare function nullToUndefined<T>(value: T | undefined | null): T | undefined;
1
+ import { Parameters } from "./types";
3
2
  export declare function excludePath(source: string, toRemove: string): string;
4
- export declare function normalizePath(path: string): string;
5
- export declare function getHash(input: string): string;
6
- export declare function getDir(file: string): string;
7
- export declare function getFileName(file: string): string;
8
- export declare function createTempDir(): void;
9
- export declare function createTempFile(name: string, content: string): string;
10
- export declare function removeTempDir(): void;
11
- export declare function generateExternalId(path: string, testName: string): string;
12
- export declare function generateFileName(): string;
13
- export declare function formatError(error: any): any;
3
+ export declare function mapParams(params: any): Parameters;
package/dist/utils.js CHANGED
@@ -1,85 +1,27 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.formatError = exports.generateFileName = exports.generateExternalId = exports.removeTempDir = exports.createTempFile = exports.createTempDir = exports.getFileName = exports.getDir = exports.getHash = exports.normalizePath = exports.excludePath = exports.nullToUndefined = exports.isDefined = void 0;
7
- const crypto_1 = require("crypto");
8
- const fs_1 = require("fs");
9
- const os_1 = require("os");
10
- const path_1 = require("path");
11
- const axios_1 = __importDefault(require("axios"));
12
- const debug_1 = require("./debug");
13
- const log = debug_1.debug.extend('utils');
14
- function isDefined(value) {
15
- return value !== undefined && value !== null;
16
- }
17
- exports.isDefined = isDefined;
18
- function nullToUndefined(value) {
19
- return value ?? undefined;
20
- }
21
- exports.nullToUndefined = nullToUndefined;
3
+ exports.mapParams = exports.excludePath = void 0;
22
4
  function excludePath(source, toRemove) {
23
5
  return source.replace(toRemove, '');
24
6
  }
25
7
  exports.excludePath = excludePath;
26
- function normalizePath(path) {
27
- return (0, path_1.normalize)(path);
28
- }
29
- exports.normalizePath = normalizePath;
30
- function getHash(input) {
31
- return (0, crypto_1.createHash)('md5').update(input).digest('hex');
32
- }
33
- exports.getHash = getHash;
34
- function getDir(file) {
35
- return (0, path_1.dirname)(file);
36
- }
37
- exports.getDir = getDir;
38
- function getFileName(file) {
39
- return (0, path_1.parse)(file).base;
40
- }
41
- exports.getFileName = getFileName;
42
- const dirPrefix = 'testit-';
43
- let tempDir;
44
- function createTempDir() {
45
- log('Creating temp dir');
46
- tempDir = (0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.tmpdir)(), dirPrefix));
47
- log('Created temp dir %s', tempDir);
48
- }
49
- exports.createTempDir = createTempDir;
50
- function createTempFile(name, content) {
51
- if (!tempDir) {
52
- throw new Error('Temp dir is not created');
53
- }
54
- log('Creating temp file %s in %s', name, tempDir);
55
- const path = (0, path_1.join)(tempDir, name);
56
- (0, fs_1.writeFileSync)(path, content);
57
- return path;
58
- }
59
- exports.createTempFile = createTempFile;
60
- function removeTempDir() {
61
- if (tempDir) {
62
- log('Removing temp dir %s', tempDir);
63
- (0, fs_1.rmSync)(tempDir, { recursive: true });
8
+ function mapParams(params) {
9
+ switch (typeof params) {
10
+ case 'string':
11
+ case 'bigint':
12
+ case 'number':
13
+ case 'boolean':
14
+ return { value: params.toString() };
15
+ case 'object':
16
+ if (params === null) {
17
+ return {};
18
+ }
19
+ return Object.keys(params).reduce((acc, key) => {
20
+ acc[key] = params[key].toString();
21
+ return acc;
22
+ }, {});
23
+ default:
24
+ return {};
64
25
  }
65
26
  }
66
- exports.removeTempDir = removeTempDir;
67
- function generateExternalId(path, testName) {
68
- return getHash(JSON.stringify({
69
- path: path,
70
- name: testName,
71
- }));
72
- }
73
- exports.generateExternalId = generateExternalId;
74
- function generateFileName() {
75
- return `${(0, crypto_1.randomUUID)()}-attachment.txt`;
76
- }
77
- exports.generateFileName = generateFileName;
78
- function formatError(error) {
79
- return axios_1.default.isAxiosError(error)
80
- ? error.response?.data ?? error.response?.statusText ?? error.message
81
- : error instanceof Error
82
- ? error.message
83
- : error;
84
- }
85
- exports.formatError = formatError;
27
+ exports.mapParams = mapParams;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "testit-adapter-jest",
3
- "version": "1.1.7",
3
+ "version": "2.0.1",
4
4
  "description": "Jest adapter for Test IT",
5
5
  "main": "dist/testitEnvironment.js",
6
6
  "scripts": {
@@ -15,13 +15,15 @@
15
15
  "license": "ISC",
16
16
  "dependencies": {
17
17
  "debug": "^4.3.4",
18
- "testit-api-client": "^1.0.8"
18
+ "testit-js-commons": "^2.0.1"
19
19
  },
20
20
  "devDependencies": {
21
21
  "@types/debug": "^4.1.7",
22
22
  "@types/jest": "^27.4.1",
23
23
  "@types/node": "^18.11.9",
24
+ "@types/request": "^2.48.8",
24
25
  "jest": "^29.5.0",
26
+ "prettier": "^3.0.1",
25
27
  "typescript": "^4.8.4"
26
28
  },
27
29
  "bugs": {
@@ -33,6 +35,7 @@
33
35
  "url": "git+https://github.com/testit-tms/adapters-js.git"
34
36
  },
35
37
  "files": [
36
- "dist"
38
+ "dist",
39
+ "types.d.ts"
37
40
  ]
38
41
  }
package/types.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { Link } from "testit-js-commons";
2
+
3
+ declare global {
4
+ const testit: {
5
+ externalId(id: string): void;
6
+ displayName(name: string): void;
7
+ links(links: Link[]): void;
8
+ labels(labels: string[]): void;
9
+ workItemIds(workItemsIds: string[]): void;
10
+ params(params: any): void;
11
+ step(name: string, description?: string): void;
12
+ title(title: string): void;
13
+ description(description: string): void;
14
+ addAttachments(attachment: string, name?: string): void;
15
+ addAttachments(attachments: string[]): void;
16
+ addAttachments(attachments: string[] | string, name?: string): void;
17
+ addLinks(link: Link): void;
18
+ addLinks(links: Link[]): void;
19
+ addMessage(message: string): void;
20
+ namespace(namespace: string): void;
21
+ classname(classname: string): void;
22
+ };
23
+ }
package/dist/config.d.ts DELETED
@@ -1 +0,0 @@
1
- export type AdapterMode = 0 | 1 | 2;
package/dist/config.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/dist/debug.d.ts DELETED
@@ -1,2 +0,0 @@
1
- import d from 'debug';
2
- export declare const debug: d.Debugger;
package/dist/debug.js DELETED
@@ -1,8 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.debug = void 0;
7
- const debug_1 = __importDefault(require("debug"));
8
- exports.debug = (0, debug_1.default)('testit');
package/dist/mappers.d.ts DELETED
@@ -1,7 +0,0 @@
1
- import { AttachmentPut, AttachmentPutModelAutotestStepResults, AutotestStep, Parameters } from 'testit-api-client';
2
- import { StepData } from './types';
3
- export declare function mapDate(date: number): string;
4
- export declare function mapStep(step: StepData): AutotestStep;
5
- export declare function mapParams(params: any): Parameters;
6
- export declare function mapStepResult(step: StepData): AttachmentPutModelAutotestStepResults;
7
- export declare function mapAttachments(attachments: string[]): AttachmentPut[];
package/dist/mappers.js DELETED
@@ -1,46 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mapAttachments = exports.mapStepResult = exports.mapParams = exports.mapStep = exports.mapDate = void 0;
4
- function mapDate(date) {
5
- return new Date(date).toISOString();
6
- }
7
- exports.mapDate = mapDate;
8
- function mapStep(step) {
9
- return {
10
- title: step.title,
11
- description: step.description,
12
- };
13
- }
14
- exports.mapStep = mapStep;
15
- function mapParams(params) {
16
- switch (typeof params) {
17
- case 'string':
18
- case 'bigint':
19
- case 'number':
20
- case 'boolean':
21
- return { value: params.toString() };
22
- case 'object':
23
- if (params === null) {
24
- return {};
25
- }
26
- return Object.keys(params).reduce((acc, key) => {
27
- acc[key] = params[key].toString();
28
- return acc;
29
- }, {});
30
- default:
31
- return {};
32
- }
33
- }
34
- exports.mapParams = mapParams;
35
- function mapStepResult(step) {
36
- return {
37
- title: step.title,
38
- description: step.description,
39
- attachments: mapAttachments(step.attachments),
40
- };
41
- }
42
- exports.mapStepResult = mapStepResult;
43
- function mapAttachments(attachments) {
44
- return attachments.map((id) => ({ id }));
45
- }
46
- exports.mapAttachments = mapAttachments;
@@ -1,18 +0,0 @@
1
- import { AutotestPost, AutotestResultsForTestRun, ClientConfig } from 'testit-api-client';
2
- export declare class TestClient {
3
- constructor(clientConfig?: Partial<ClientConfig>);
4
- private client;
5
- private _testRunId;
6
- get testRunId(): string;
7
- get projectId(): string;
8
- get configurationId(): string;
9
- createTestRun(): Promise<string>;
10
- startTestRun(): Promise<void>;
11
- completeTestRun(): Promise<void>;
12
- loadAutotest(autotestPost: AutotestPost): Promise<string>;
13
- loadPassedAutotest(autotest: AutotestPost): Promise<void>;
14
- getAutotestId(externalId: string): Promise<string>;
15
- linkWorkItem(externalId: string, workItemId: string): Promise<void>;
16
- loadAutotestResults(results: AutotestResultsForTestRun[]): Promise<void>;
17
- uploadAttachments(attachments: string[]): Promise<string[]>;
18
- }
@@ -1,128 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TestClient = void 0;
4
- const testit_api_client_1 = require("testit-api-client");
5
- const debug_1 = require("./debug");
6
- const utils_1 = require("./utils");
7
- const log = debug_1.debug.extend('client');
8
- class TestClient {
9
- constructor(clientConfig = {}) {
10
- this.client = new testit_api_client_1.Client(clientConfig);
11
- this._testRunId = clientConfig.testRunId;
12
- }
13
- get testRunId() {
14
- if (this._testRunId === undefined) {
15
- throw new Error('Test run id is not set');
16
- }
17
- return this._testRunId;
18
- }
19
- get projectId() {
20
- return this.client.getConfig().projectId;
21
- }
22
- get configurationId() {
23
- return this.client.getConfig().configurationId;
24
- }
25
- async createTestRun() {
26
- const { projectId, testRunId } = this.client.getConfig();
27
- if (testRunId === undefined) {
28
- log('Test run id is not provided, creating test run for project %s', projectId);
29
- this._testRunId = await this.client
30
- .createTestRun({ projectId })
31
- .then((testRun) => testRun.id);
32
- }
33
- else {
34
- log('Using provided test run id %s', testRunId);
35
- this._testRunId = testRunId;
36
- }
37
- log('Starting test run %s', this.testRunId);
38
- return this.testRunId;
39
- }
40
- async startTestRun() {
41
- log('Starting test run %s', this.testRunId);
42
- await this.client.startTestRun(this.testRunId);
43
- }
44
- async completeTestRun() {
45
- log('Completing test run %s', this.testRunId);
46
- const testRun = await this.client.getTestRun(this.testRunId);
47
- if (testRun.stateName === 'InProgress') {
48
- await this.client.completeTestRun(this.testRunId);
49
- }
50
- }
51
- async loadAutotest(autotestPost) {
52
- try {
53
- log('Creating autotest %o', autotestPost);
54
- const { id } = await this.client.createAutotest(autotestPost);
55
- return id;
56
- }
57
- catch (err) {
58
- const axiosError = err;
59
- if (axiosError.response?.status === 409) {
60
- log('Autotest %s already exists, updating with %o', autotestPost.externalId, autotestPost);
61
- const [autotest] = await this.client.getAutotest({
62
- projectId: this.client.getConfig().projectId,
63
- externalId: autotestPost.externalId,
64
- });
65
- await this.client.updateAutotest({
66
- ...autotest,
67
- links: autotest.links,
68
- });
69
- return autotest.id;
70
- }
71
- else {
72
- console.error((0, utils_1.formatError)(err));
73
- throw err;
74
- }
75
- }
76
- }
77
- async loadPassedAutotest(autotest) {
78
- try {
79
- log('Creating autotest %o', autotest);
80
- await this.client.createAutotest(autotest);
81
- }
82
- catch (err) {
83
- const axiosError = err;
84
- if (axiosError.response?.status === 409) {
85
- log('Autotest %s already exists, updating with %o', autotest.externalId, autotest);
86
- await this.client.updateAutotest(autotest);
87
- }
88
- else {
89
- console.error((0, utils_1.formatError)(err));
90
- throw err;
91
- }
92
- }
93
- }
94
- async getAutotestId(externalId) {
95
- const [autotest] = await this.client.getAutotest({
96
- projectId: this.client.getConfig().projectId,
97
- externalId,
98
- });
99
- return autotest.id;
100
- }
101
- async linkWorkItem(externalId, workItemId) {
102
- log('Linking work item %s to autotest %s', workItemId, externalId);
103
- return this.client.linkToWorkItem(externalId, { id: workItemId });
104
- }
105
- async loadAutotestResults(results) {
106
- log('Loading autotest results %o', results);
107
- await this.client.loadTestRunResults(this.testRunId, results);
108
- }
109
- async uploadAttachments(attachments) {
110
- const attachmentIds = [];
111
- for (const attachment of attachments) {
112
- try {
113
- log('Uploading attachment %s', attachment);
114
- const { id } = await this.client.loadAttachment(attachment);
115
- if (!id) {
116
- log('Attachment id is not returned');
117
- continue;
118
- }
119
- attachmentIds.push(id);
120
- }
121
- catch (err) {
122
- console.error(`Failed to load attachment`, (0, utils_1.formatError)(err));
123
- }
124
- }
125
- return attachmentIds;
126
- }
127
- }
128
- exports.TestClient = TestClient;