@teambit/tester 0.0.554 → 0.0.558

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.
@@ -1,245 +0,0 @@
1
- import fs from 'fs-extra';
2
- import { CLIAspect, CLIMain, MainRuntime } from '@teambit/cli';
3
- import { Component } from '@teambit/component';
4
- import compact from 'lodash.compact';
5
- import { EnvsAspect, EnvsExecutionResult, EnvsMain } from '@teambit/envs';
6
- import { LoggerAspect, LoggerMain } from '@teambit/logger';
7
- import { Workspace, WorkspaceAspect } from '@teambit/workspace';
8
- import { GraphqlAspect, GraphqlMain } from '@teambit/graphql';
9
- import { BuilderAspect, BuilderMain } from '@teambit/builder';
10
- import { UiMain, UIAspect } from '@teambit/ui';
11
- import { merge } from 'lodash';
12
- import DevFilesAspect, { DevFilesMain } from '@teambit/dev-files';
13
- import { TestsResult } from '@teambit/tests-results';
14
- import { ComponentsResults, CallbackFn, Tests } from './tester';
15
- import { TestCmd } from './test.cmd';
16
- import { TesterAspect } from './tester.aspect';
17
- import { TesterService } from './tester.service';
18
- import { TesterTask } from './tester.task';
19
- import { detectTestFiles } from './utils';
20
- import { testerSchema } from './tester.graphql';
21
- import { testsResultsToJUnitFormat } from './utils/junit-generator';
22
-
23
- export type TesterExtensionConfig = {
24
- /**
25
- * regex of the text environment.
26
- */
27
- testRegex: string;
28
-
29
- /**
30
- * determine whether to watch on start.
31
- */
32
- watchOnStart: boolean;
33
- patterns: string[];
34
- };
35
-
36
- export type TesterOptions = {
37
- /**
38
- * start the tester in watch mode.
39
- */
40
- watch: boolean;
41
-
42
- /**
43
- * start the tester in debug mode.
44
- */
45
- debug: boolean;
46
-
47
- /**
48
- * start the tester in debug mode.
49
- */
50
- ui?: boolean;
51
-
52
- /**
53
- * initiate the tester on given env.
54
- */
55
- env?: string;
56
-
57
- /**
58
- * generate JUnit files on the specified dir
59
- */
60
- junit?: string;
61
-
62
- /**
63
- * show code coverage
64
- */
65
- coverage?: boolean;
66
-
67
- callback?: CallbackFn;
68
- };
69
-
70
- export class TesterMain {
71
- static runtime = MainRuntime;
72
- static dependencies = [
73
- CLIAspect,
74
- EnvsAspect,
75
- WorkspaceAspect,
76
- LoggerAspect,
77
- GraphqlAspect,
78
- UIAspect,
79
- DevFilesAspect,
80
- BuilderAspect,
81
- ];
82
-
83
- constructor(
84
- /**
85
- * graphql extension.
86
- */
87
- private graphql: GraphqlMain,
88
-
89
- /**
90
- * envs extension.
91
- */
92
- private envs: EnvsMain,
93
-
94
- /**
95
- * workspace extension.
96
- */
97
- private workspace: Workspace,
98
-
99
- /**
100
- * tester service.
101
- */
102
- readonly service: TesterService,
103
-
104
- /**
105
- * build task.
106
- */
107
- readonly task: TesterTask,
108
-
109
- private devFiles: DevFilesMain,
110
-
111
- private builder: BuilderMain
112
- ) {}
113
-
114
- _testsResults: { [componentId: string]: ComponentsResults } | undefined[] = [];
115
-
116
- async test(components: Component[], opts?: TesterOptions): Promise<EnvsExecutionResult<Tests>> {
117
- const options = this.getOptions(opts);
118
- const envsRuntime = await this.envs.createEnvironment(components);
119
- if (opts?.env) {
120
- return envsRuntime.runEnv(opts.env, this.service, options);
121
- }
122
- const results = await envsRuntime.run(this.service, options);
123
- if (opts?.junit) {
124
- await this.generateJUnit(opts?.junit, results);
125
- }
126
- return results;
127
- }
128
-
129
- private async generateJUnit(filePath: string, testsResults: EnvsExecutionResult<Tests>) {
130
- const components = testsResults.results.map((envResult) => envResult.data?.components).flat();
131
- const jUnit = testsResultsToJUnitFormat(compact(components));
132
- await fs.outputFile(filePath, jUnit);
133
- }
134
-
135
- /**
136
- * watch all components for changes and test upon each.
137
- */
138
- async watch(components: Component[], opts?: TesterOptions) {
139
- const options = this.getOptions(opts);
140
- const envsRuntime = await this.envs.createEnvironment(components);
141
- if (opts?.env) {
142
- return envsRuntime.runEnv(opts.env, this.service, options);
143
- }
144
-
145
- this.service.onTestRunComplete((results) => {
146
- results.components.forEach((component) => {
147
- this._testsResults[component.componentId.toString()] = component;
148
- });
149
- });
150
- return envsRuntime.run(this.service, options);
151
- }
152
-
153
- async uiWatch() {
154
- const components = await this.workspace.list();
155
- return this.watch(components, { watch: true, debug: false, ui: true });
156
- }
157
-
158
- async getTestsResults(component: Component): Promise<{ testsResults?: TestsResult; loading: boolean } | undefined> {
159
- const entry = component.state.aspects.get(TesterAspect.id);
160
- const componentStatus = await this.workspace?.getComponentStatus(component);
161
- const data = this.builder.getDataByAspect(component, TesterAspect.id) as { tests: TestsResult };
162
- if ((entry || data) && !componentStatus?.modifyInfo?.hasModifiedFiles) {
163
- return { testsResults: data?.tests || entry?.data.tests, loading: false };
164
- }
165
- return this.getTestsResultsFromState(component);
166
- }
167
-
168
- private getTestsResultsFromState(component: Component) {
169
- const tests = this._testsResults[component.id.toString()];
170
- return { testsResults: tests?.results, loading: tests?.loading || false };
171
- }
172
-
173
- /**
174
- * get all test files of a component.
175
- */
176
- getTestFiles(component: Component) {
177
- return detectTestFiles(component, this.devFiles);
178
- }
179
-
180
- private getOptions(options?: TesterOptions): TesterOptions {
181
- const defaults = {
182
- watch: false,
183
- debug: false,
184
- };
185
-
186
- return merge(defaults, options);
187
- }
188
-
189
- static defaultConfig = {
190
- /**
191
- * default test regex for which files tester to apply on.
192
- */
193
- patterns: ['**/*.spec.+(js|ts|jsx|tsx)', '**/*.test.+(js|ts|jsx|tsx)'],
194
-
195
- /**
196
- * determine whether to watch on start.
197
- */
198
- watchOnStart: true,
199
- };
200
-
201
- static async provider(
202
- [cli, envs, workspace, loggerAspect, graphql, ui, devFiles, builder]: [
203
- CLIMain,
204
- EnvsMain,
205
- Workspace,
206
- LoggerMain,
207
- GraphqlMain,
208
- UiMain,
209
- DevFilesMain,
210
- BuilderMain
211
- ],
212
- config: TesterExtensionConfig
213
- ) {
214
- const logger = loggerAspect.createLogger(TesterAspect.id);
215
- const testerService = new TesterService(workspace, config.patterns, logger, graphql.pubsub, devFiles);
216
- envs.registerService(testerService);
217
- devFiles.registerDevPattern(config.patterns);
218
- const tester = new TesterMain(
219
- graphql,
220
- envs,
221
- workspace,
222
- testerService,
223
- new TesterTask(TesterAspect.id, devFiles),
224
- devFiles,
225
- builder
226
- );
227
-
228
- if (workspace && !workspace.consumer.isLegacy) {
229
- cli.unregister('test');
230
- ui.registerOnStart(async () => {
231
- if (!config.watchOnStart) return undefined;
232
- await tester.uiWatch();
233
- return undefined;
234
- });
235
-
236
- cli.register(new TestCmd(tester, workspace, logger));
237
- }
238
-
239
- graphql.register(testerSchema(tester, graphql));
240
-
241
- return tester;
242
- }
243
- }
244
-
245
- TesterAspect.addRuntime(TesterMain);
@@ -1,161 +0,0 @@
1
- import { Logger } from '@teambit/logger';
2
- import { resolve } from 'path';
3
- import React from 'react';
4
- import { Text, Newline } from 'ink';
5
- import { EnvService, ExecutionContext, EnvDefinition } from '@teambit/envs';
6
- import { ComponentMap } from '@teambit/component';
7
- import { Workspace } from '@teambit/workspace';
8
- import highlight from 'cli-highlight';
9
- import { PubSub } from 'graphql-subscriptions';
10
- import { DevFilesMain } from '@teambit/dev-files';
11
- import { Tester, Tests, CallbackFn } from './tester';
12
- import { TesterAspect } from './tester.aspect';
13
- import { TesterOptions } from './tester.main.runtime';
14
- import { detectTestFiles } from './utils';
15
- import { NoTestFilesFound } from './exceptions';
16
-
17
- const chalk = require('chalk');
18
-
19
- export const OnTestsChanged = 'OnTestsChanged';
20
-
21
- export type TesterDescriptor = {
22
- /**
23
- * id of the tester (e.g. jest/mocha)
24
- */
25
- id: string;
26
-
27
- /**
28
- * display name of the tester (e.g. Jest / Mocha)
29
- */
30
- displayName: string;
31
-
32
- /**
33
- * icon of the configured tester.
34
- */
35
- icon: string;
36
-
37
- /**
38
- * string containing the config for display.
39
- */
40
- config: string;
41
-
42
- version?: string;
43
- };
44
-
45
- export class TesterService implements EnvService<Tests, TesterDescriptor> {
46
- name = 'tester';
47
-
48
- constructor(
49
- readonly workspace: Workspace,
50
- /**
51
- * regex used to identify which files to test.
52
- */
53
- readonly patterns: string[],
54
-
55
- private logger: Logger,
56
-
57
- private pubsub: PubSub,
58
-
59
- private devFiles: DevFilesMain
60
- ) {}
61
-
62
- _callback: CallbackFn | undefined;
63
-
64
- render(env: EnvDefinition) {
65
- const descriptor = this.getDescriptor(env);
66
- return (
67
- <Text key={descriptor?.id}>
68
- <Text color="cyan">configured tester: </Text>
69
- <Text>
70
- {descriptor?.id} ({descriptor?.displayName} @ {descriptor?.version})
71
- </Text>
72
- <Newline />
73
- <Text underline color="cyan">
74
- tester config:
75
- </Text>
76
- <Newline />
77
- <Text>
78
- {/* refactor a separate component which highlights for cli */}
79
- {highlight(descriptor?.config || '', { language: 'javascript', ignoreIllegals: true })}
80
- </Text>
81
- <Newline />
82
- </Text>
83
- );
84
- }
85
-
86
- getDescriptor(environment: EnvDefinition) {
87
- if (!environment.env.getTester) return undefined;
88
- const tester: Tester = environment.env.getTester();
89
-
90
- return {
91
- id: tester.id || '',
92
- displayName: tester.displayName || '',
93
- icon: tester.icon || '',
94
- config: tester.displayConfig ? tester.displayConfig() : '',
95
- version: tester.version ? tester.version() : '?',
96
- };
97
- }
98
-
99
- onTestRunComplete(callback: CallbackFn) {
100
- this._callback = callback;
101
- }
102
-
103
- async run(context: ExecutionContext, options: TesterOptions): Promise<Tests> {
104
- const tester: Tester = context.env.getTester();
105
- const specFiles = ComponentMap.as(context.components, (component) => {
106
- return detectTestFiles(component, this.devFiles);
107
- });
108
- const testCount = specFiles.toArray().reduce((acc, [, specs]) => acc + specs.length, 0);
109
-
110
- const componentWithTests = specFiles.toArray().reduce((acc: number, [, specs]) => {
111
- if (specs.length > 0) acc += 1;
112
- return acc;
113
- }, 0);
114
-
115
- if (testCount === 0 && !options.ui) throw new NoTestFilesFound(this.patterns.join(','));
116
-
117
- if (!options.ui)
118
- this.logger.console(`testing ${componentWithTests} components with environment ${chalk.cyan(context.id)}\n`);
119
-
120
- const patterns = ComponentMap.as(context.components, (component) => {
121
- const dir = this.workspace.componentDir(component.id);
122
- const componentPatterns = this.devFiles.getDevPatterns(component, TesterAspect.id);
123
- return componentPatterns.map((pattern: string) => ({ path: resolve(dir, pattern), relative: pattern }));
124
- });
125
-
126
- const testerContext = Object.assign(context, {
127
- release: false,
128
- specFiles,
129
- patterns,
130
- rootPath: this.workspace.path,
131
- workspace: this.workspace,
132
- debug: options.debug,
133
- watch: options.watch,
134
- ui: options.ui,
135
- coverage: options.coverage,
136
- });
137
-
138
- if (options.watch && options.ui && tester.watch) {
139
- if (tester.onTestRunComplete) {
140
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
141
- tester.onTestRunComplete((results) => {
142
- if (this._callback) this._callback(results);
143
- results.components.forEach((component) => {
144
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
145
- this.pubsub.publish(OnTestsChanged, {
146
- testsChanged: {
147
- id: component.componentId.toString(),
148
- testsResults: component.results,
149
- loading: component.loading,
150
- },
151
- });
152
- });
153
- });
154
- }
155
-
156
- return tester.watch(testerContext);
157
- }
158
-
159
- return tester.test(testerContext);
160
- }
161
- }
package/tester.task.ts DELETED
@@ -1,111 +0,0 @@
1
- import { BuildContext, BuiltTaskResult, BuildTask } from '@teambit/builder';
2
- import fs from 'fs-extra';
3
- import { join } from 'path';
4
- import { Compiler, CompilerAspect } from '@teambit/compiler';
5
- import { DevFilesMain } from '@teambit/dev-files';
6
- import { ComponentMap } from '@teambit/component';
7
- import { Tester } from './tester';
8
- import { detectTestFiles } from './utils';
9
- import { testsResultsToJUnitFormat } from './utils/junit-generator';
10
-
11
- const JUNIT_PATH = '__bit_junit.xml';
12
-
13
- /**
14
- * tester build task. Allows to test components during component build.
15
- */
16
- export class TesterTask implements BuildTask {
17
- readonly name = 'TestComponents';
18
- readonly dependencies = [CompilerAspect.id];
19
- constructor(readonly aspectId: string, private devFiles: DevFilesMain) {}
20
-
21
- async execute(context: BuildContext): Promise<BuiltTaskResult> {
22
- const tester: Tester = context.env.getTester();
23
- const componentsSpecFiles = ComponentMap.as(context.components, (component) => {
24
- return detectTestFiles(component, this.devFiles);
25
- });
26
-
27
- const testCount = componentsSpecFiles.toArray().reduce((acc, [, specs]) => acc + specs.length, 0);
28
- if (testCount === 0)
29
- return {
30
- artifacts: [],
31
- componentsResults: [],
32
- };
33
-
34
- const specFilesWithCapsule = ComponentMap.as(context.components, (component) => {
35
- const componentSpecFiles = componentsSpecFiles.get(component);
36
- if (!componentSpecFiles) throw new Error('capsule not found');
37
- const [, specs] = componentSpecFiles;
38
- return specs.map((specFile) => {
39
- const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);
40
- if (!capsule) throw new Error('capsule not found');
41
- const compiler: Compiler = context.env.getCompiler();
42
- const distPath = compiler.getDistPathBySrcPath(specFile.relative);
43
-
44
- // TODO: fix spec type file need to capsule will return files with type AbstractVinyl
45
- return { path: join(capsule.path, distPath), relative: distPath };
46
- });
47
- });
48
-
49
- const testerContext = Object.assign(context, {
50
- release: true,
51
- specFiles: specFilesWithCapsule,
52
- rootPath: context.capsuleNetwork.capsulesRootDir,
53
- patterns: specFilesWithCapsule,
54
- });
55
-
56
- // TODO: remove after fix AbstractVinyl on capsule
57
- // @ts-ignore
58
- const testsResults = await tester.test(testerContext);
59
-
60
- // write junit files
61
- await Promise.all(
62
- testsResults.components.map(async (compResult) => {
63
- const junit = testsResultsToJUnitFormat([compResult]);
64
- const capsule = context.capsuleNetwork.graphCapsules.getCapsule(compResult.componentId);
65
- if (!capsule) {
66
- throw new Error(`unable to find ${compResult.componentId.toString()} in capsules`);
67
- }
68
- await fs.writeFile(join(capsule.path, JUNIT_PATH), junit);
69
- await this.writeNpmIgnore(capsule.path);
70
- })
71
- );
72
-
73
- return {
74
- artifacts: [
75
- {
76
- name: 'junit',
77
- globPatterns: [JUNIT_PATH],
78
- },
79
- ], // @ts-ignore
80
- componentsResults: testsResults.components.map((componentTests) => {
81
- const componentErrors = componentTests.results?.testFiles.reduce((errors: string[], file) => {
82
- if (file?.error?.failureMessage) {
83
- errors.push(file.error.failureMessage);
84
- }
85
- file.tests.forEach((test) => {
86
- if (test.error) errors.push(test.error);
87
- if (test.failure) errors.push(test.failure);
88
- });
89
-
90
- return errors;
91
- }, []);
92
- const component = context.capsuleNetwork.graphCapsules.getCapsule(componentTests.componentId)?.component;
93
- if (!component) {
94
- throw new Error(`unable to find ${componentTests.componentId.toString()} in capsules`);
95
- }
96
- return {
97
- component,
98
- metadata: { tests: componentTests.results },
99
- errors: componentErrors,
100
- };
101
- }),
102
- };
103
- }
104
-
105
- private async writeNpmIgnore(dir: string) {
106
- const NPM_IGNORE_FILE = '.npmignore';
107
- const npmIgnorePath = join(dir, NPM_IGNORE_FILE);
108
- const npmIgnoreEntriesStr = `\n${JUNIT_PATH}\n`;
109
- await fs.appendFile(npmIgnorePath, npmIgnoreEntriesStr);
110
- }
111
- }
package/tester.ts DELETED
@@ -1,126 +0,0 @@
1
- import { Component, ComponentID, ComponentMap } from '@teambit/component';
2
- import { ExecutionContext } from '@teambit/envs';
3
- import { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';
4
- import { TestsResult } from '@teambit/tests-results';
5
-
6
- export type Tests = {
7
- components: ComponentsResults[];
8
- errors?: Error[];
9
- };
10
-
11
- export type ComponentsResults = {
12
- componentId: ComponentID;
13
- results?: TestsResult;
14
- loading?: boolean;
15
- };
16
-
17
- export type SpecFiles = ComponentMap<AbstractVinyl[]>;
18
- export type ComponentPatternsMap = ComponentMap<{ path: string; relative: string }[]>;
19
-
20
- export interface TesterContext extends ExecutionContext {
21
- /**
22
- * whether the tester run for release (during bit build/tag) or not (during bit test command).
23
- */
24
- release: boolean;
25
-
26
- /**
27
- * list of components to test.
28
- */
29
- components: Component[];
30
-
31
- /**
32
- * component workspace.
33
- */
34
- // workspace: Workspace;
35
-
36
- /**
37
- * defines whether tester is expected to run in quiet mode.
38
- */
39
- quiet?: boolean;
40
-
41
- /**
42
- * list of spec files to test.
43
- */
44
- specFiles: SpecFiles;
45
-
46
- /**
47
- * rootPath of the component workspace or the capsule root dir (during build).
48
- */
49
- rootPath: string;
50
-
51
- /**
52
- * determines whether tester is expected to run in debug mode.
53
- */
54
- debug?: boolean;
55
-
56
- /**
57
- * is start from ui
58
- */
59
- ui?: boolean;
60
-
61
- /**
62
- * determines whether to start the tester in watch mode.
63
- */
64
- watch?: boolean;
65
-
66
- /**
67
- * whether the tester should show code coverage
68
- */
69
- coverage?: boolean;
70
-
71
- /**
72
- * array of patterns to test.
73
- */
74
- patterns: ComponentPatternsMap;
75
- }
76
-
77
- /**
78
- * tester interface allows extensions to implement a component tester into bit.
79
- */
80
- export interface Tester {
81
- /**
82
- * display name of the tester.
83
- */
84
- displayName?: string;
85
-
86
- /**
87
- * icon of the tester.
88
- */
89
- icon?: string;
90
-
91
- /**
92
- * serialized config of the tester.
93
- */
94
- displayConfig?(): string;
95
-
96
- /**
97
- * path to the config in the filesystem.
98
- */
99
- configPath?: string;
100
-
101
- /**
102
- * id of the tester.
103
- */
104
- id: string;
105
-
106
- /**
107
- * on test run complete. (applies only during watch)
108
- * @param callback
109
- */
110
- onTestRunComplete?(callback: CallbackFn): Promise<void>;
111
-
112
- /**
113
- * execute tests on all components in the given execution context.
114
- */
115
- test(context: TesterContext): Promise<Tests>;
116
-
117
- /**
118
- * watch tests on all components
119
- */
120
- watch?(context: TesterContext): Promise<Tests>;
121
- /**
122
- * return the tester version.
123
- */
124
- version(): string;
125
- }
126
- export type CallbackFn = (testSuite: Tests) => void;
@@ -1,42 +0,0 @@
1
- import { ComponentType } from 'react';
2
- import { UIRuntime } from '@teambit/ui';
3
- import { SlotRegistry, Slot } from '@teambit/harmony';
4
- import { ComponentAspect, ComponentUI } from '@teambit/component';
5
- import { TestsSection } from './tests.section';
6
- import { TesterAspect } from './tester.aspect';
7
-
8
- export type EmptyStateSlot = SlotRegistry<ComponentType>;
9
- export class TesterUI {
10
- static dependencies = [ComponentAspect];
11
-
12
- static runtime = UIRuntime;
13
-
14
- stageKey?: string;
15
-
16
- constructor(private component: ComponentUI, private emptyStateSlot: EmptyStateSlot) {}
17
-
18
- /**
19
- * register a new tester empty state. this allows to register a different empty state from each environment for example.
20
- */
21
- registerEmptyState(emptyStateComponent: ComponentType) {
22
- this.emptyStateSlot.register(emptyStateComponent);
23
- return this;
24
- }
25
-
26
- static slots = [Slot.withType<ComponentType>()];
27
-
28
- static async provider([component]: [ComponentUI], config, [emptyStateSlot]: [EmptyStateSlot]) {
29
- const testerUi = new TesterUI(component, emptyStateSlot);
30
-
31
- const section = new TestsSection(emptyStateSlot);
32
-
33
- component.registerRoute(section.route);
34
- component.registerNavigation(section.navigationLink, section.order);
35
-
36
- return testerUi;
37
- }
38
- }
39
-
40
- export default TesterUI;
41
-
42
- TesterAspect.addRuntime(TesterUI);
package/tests.section.tsx DELETED
@@ -1,18 +0,0 @@
1
- import React from 'react';
2
- import { Section } from '@teambit/component';
3
- import { TestsPage } from './ui/tests-page';
4
- import { EmptyStateSlot } from './tester.ui.runtime';
5
-
6
- export class TestsSection implements Section {
7
- constructor(private emptyStateSlot: EmptyStateSlot) {}
8
-
9
- route = {
10
- path: '~tests',
11
- children: <TestsPage emptyState={this.emptyStateSlot} />,
12
- };
13
- navigationLink = {
14
- href: '~tests',
15
- children: 'Tests',
16
- };
17
- order = 40;
18
- }