### Install Dependencies Source: https://github.com/ctrf-io/ctrf-js/blob/main/CONTRIBUTING.md Run this command to install all necessary project dependencies before starting local development. ```bash npm install ``` -------------------------------- ### start() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets the start timestamp for the test. ```APIDOC ## start() ### Description Set the start timestamp. ### Parameters #### timestamp (`number`) - Optional: No - Description: The start timestamp of the test. ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### Install CTRF Source: https://github.com/ctrf-io/ctrf-js/blob/main/README.md Install the CTRF package using npm. ```sh npm install ctrf ``` -------------------------------- ### Quick Start: Build and Validate a CTRF Report Source: https://github.com/ctrf-io/ctrf-js/blob/main/src/README.md Build a CTRF report using the fluent API and then validate it. This example demonstrates creating a report with multiple tests and checking its validity. ```typescript import { ctrf } from 'ctrf' // Build a report using the fluent API const report = new ctrf.ReportBuilder() .tool({ name: 'jest', version: '29.0.0' }) .addTest( new ctrf.TestBuilder() .name('should add numbers') .status('passed') .duration(150) .build() ) .addTest( new ctrf.TestBuilder() .name('should handle errors') .status('failed') .duration(200) .message('Expected 5 but got 4') .build() ) .build() // Validate the report const result = ctrf.validateStrict(report) if (!result.valid) { console.error('Validation errors:', result.errors) } // Write to file await ctrf.writeReport(report, './ctrf-report.json') ``` -------------------------------- ### Run CTRF.js Migration Tests Source: https://github.com/ctrf-io/ctrf-js/blob/main/MIGRATION.md Commands to install dependencies and run tests after migrating to CTRF.js v0.1.0. ```bash npm install npm test ``` -------------------------------- ### CTRF Quick Start Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Demonstrates basic usage of CTRF functions including validation, parsing, and programmatic report building. ```typescript import { validate, parse, ReportBuilder, TestBuilder, filterTests, merge, } from 'ctrf' // Validate a report const result = validate(report) if (result.valid) { console.log('Report is valid!') } // Parse JSON const report = parse(jsonString, { validate: true }) // Build reports programmatically const report = new ReportBuilder() .tool({ name: 'jest', version: '29.0.0' }) .addTest( new TestBuilder() .name('should add numbers') .status('passed') .duration(150) .build() ) .build() ``` -------------------------------- ### Quick Start: Build and Validate Report Source: https://github.com/ctrf-io/ctrf-js/blob/main/README.md Build a CTRF report using the fluent API and validate it. ```typescript import { ReportBuilder, TestBuilder, validateStrict } from 'ctrf' // Build a report using the fluent API const report = new ReportBuilder() .tool({ name: 'jest', version: '29.0.0' }) .addTest( new TestBuilder() .name('should add numbers') .status('passed') .duration(150) .build() ) .addTest( new TestBuilder() .name('should handle errors') .status('failed') .duration(200) .message('Expected 5 but got 4') .build() ) .build() // Validate the report validateStrict(report) ``` -------------------------------- ### SummaryOptions Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/interfaces/SummaryOptions.md Options for calculating summary data. Allows specifying optional start and stop timestamps. ```APIDOC ## Interface: SummaryOptions Defined in: [types.ts:476](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L476) Options for calculating summary ### Properties #### start? > `optional` **start?**: `number` Defined in: [types.ts:478](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L478) Start timestamp *** #### stop? > `optional` **stop?**: `number` Defined in: [types.ts:480](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L480) Stop timestamp ``` -------------------------------- ### Complete CTRF.js Example Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Demonstrates building, validating, filtering, serializing, adding insights, and merging CTRF reports using the CTRF.js library. ```typescript import { ReportBuilder, TestBuilder, validate, stringify, filterTests, addInsights, merge, type CTRFReport, type Test, } from 'ctrf' // Build a report const report = new ReportBuilder({ autoGenerateId: true, autoTimestamp: true }) .tool({ name: 'vitest', version: '1.0.0' }) .environment({ branchName: 'main', commit: 'abc123', buildNumber: '42', }) .addTest( new TestBuilder({ autoGenerateId: true }) .name('should create user') .suite(['API', 'Users']) .status('passed') .duration(120) .filePath('tests/api/users.test.ts') .tags(['api', 'smoke']) .build() ) .addTest( new TestBuilder({ autoGenerateId: true }) .name('should delete user') .suite(['API', 'Users']) .status('failed') .duration(85) .message('User not found') .trace('Error: User not found\n at deleteUser (users.ts:42)') .filePath('tests/api/users.test.ts') .build() ) .build() // Validate const result = validate(report) console.log('Valid:', result.valid) // Filter failed tests const failed = filterTests(report, { status: 'failed' }) console.log('Failed tests:', failed.length) // Serialize const json = stringify(report, { pretty: true }) // Add insights from history const reportWithInsights = addInsights(report, previousReports) // Merge parallel runs const merged = merge([shard1, shard2, shard3], { deduplicateTests: true, }) ``` -------------------------------- ### Build a CTRF Report with Tests Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Example demonstrating how to use ReportBuilder and TestBuilder to create a CTRF report with multiple tests, including status, duration, and messages. ```typescript import { ReportBuilder, TestBuilder } from 'ctrf' const report = new ReportBuilder({ autoGenerateId: true, autoTimestamp: true }) .specVersion('0.0.0') .tool({ name: 'jest', version: '29.0.0' }) .environment({ branchName: 'main', commit: 'abc123' }) .addTest( new TestBuilder() .name('should add numbers') .status('passed') .duration(150) .build() ) .addTest( new TestBuilder() .name('should handle errors') .status('failed') .duration(200) .message('Expected 5 but got 4') .build() ) .build() ``` -------------------------------- ### Build a Test Object Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Example of creating a Test object using TestBuilder, specifying details like name, suite, status, duration, file path, and tags. ```typescript import { TestBuilder } from 'ctrf' const test = new TestBuilder({ autoGenerateId: true }) .name('should validate user input') .suite(['Authentication', 'Login']) .status('passed') .duration(245) .filePath('tests/auth/login.test.ts') .tags(['smoke', 'auth']) .type('integration') .build() ``` -------------------------------- ### Calculate Summary with Tests and Timing Options Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/functions/calculateSummary.md Usage of calculateSummary with optional timing information. Provide 'start' and 'stop' timestamps in milliseconds to include timing in the summary. ```typescript const summary = calculateSummary(tests, { start: 1704067200000, stop: 1704067260000 }); ``` -------------------------------- ### Reading and Writing CTRF Reports Source: https://github.com/ctrf-io/ctrf-js/blob/main/src/README.md Provides examples for asynchronous and synchronous file operations to read and write CTRF reports. Also includes methods for parsing JSON strings and stringifying reports with formatting options. ```typescript import { ctrf } from 'ctrf' // Async file operations const report = await ctrf.readReport('./ctrf-report.json') await ctrf.writeReport(report, './output.json') // Sync file operations const reportSync = ctrf.readReportSync('./ctrf-report.json') ctrf.writeReportSync(report, './output.json') // Parse from string const parsed = ctrf.parse(jsonString) // Stringify with formatting const json = ctrf.stringify(report, { pretty: true, indent: 2 }) ``` -------------------------------- ### Constructing a CTRF Report Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/ReportBuilder.md Use ReportBuilder to create a CTRF report object. This example demonstrates setting the spec version, tool, environment, and adding a test using TestBuilder. ```typescript const report = new ReportBuilder() .specVersion('1.0.0') .tool({ name: 'jest', version: '29.0.0' }) .environment({ branchName: 'main' }) .addTest( new TestBuilder() .name('should add numbers') .status('passed') .duration(150) .build() ) .build(); ``` -------------------------------- ### Get Current Spec Version Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Returns the currently active CTRF specification version string. ```typescript function getCurrentSpecVersion(): string ``` -------------------------------- ### Summary Interface Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/interfaces/Summary.md This interface defines the structure for aggregated test statistics. It includes various counts related to test execution, timestamps for the start and stop of tests, and optional fields for duration and custom metadata. ```APIDOC ## Interface: Summary Defined in: [types.ts:73](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L73) Aggregated test statistics ### Properties - **tests** (`number`) - Total number of tests. Defined in: [types.ts:75](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L75) - **passed** (`number`) - Number of passed tests. Defined in: [types.ts:77](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L77) - **failed** (`number`) - Number of failed tests. Defined in: [types.ts:79](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L79) - **skipped** (`number`) - Number of skipped tests. Defined in: [types.ts:81](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L81) - **pending** (`number`) - Number of pending tests. Defined in: [types.ts:83](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L83) - **other** (`number`) - Number of tests with other status. Defined in: [types.ts:85](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L85) - **flaky?** (`number` | `undefined`) - Optional. Number of flaky tests. Defined in: [types.ts:87](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L87) - **suites?** (`number` | `undefined`) - Optional. Number of test suites. Defined in: [types.ts:89](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L89) - **start** (`number`) - Start timestamp (Unix epoch milliseconds). Defined in: [types.ts:91](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L91) - **stop** (`number`) - Stop timestamp (Unix epoch milliseconds). Defined in: [types.ts:93](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L93) - **duration?** (`number` | `undefined`) - Optional. Total duration in milliseconds. Defined in: [types.ts:95](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L95) - **extra?** (`Record` | `undefined`) - Optional. Custom metadata. Defined in: [types.ts:97](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L97) ``` -------------------------------- ### Get CTRF Version Information Source: https://github.com/ctrf-io/ctrf-js/blob/main/src/README.md Access the current and supported specification versions for CTRF. This helps in ensuring compatibility and understanding versioning. ```typescript // Get version info const version = ctrf.getCurrentSpecVersion() // '1.0.0' const supported = ctrf.getSupportedSpecVersions() // ['1.0.0'] ``` -------------------------------- ### Get CTRF Schema for Specific Versions Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/functions/getSchema.md Use getSchema with a version string (e.g., '0.0.0' or '1.0.0') to retrieve the corresponding JSON schema object. Ensure the version is supported to avoid errors. ```typescript const v0_0Schema = getSchema('0.0.0'); const v1_0Schema = getSchema('1.0.0'); ``` -------------------------------- ### Build the Package Source: https://github.com/ctrf-io/ctrf-js/blob/main/CONTRIBUTING.md Run this command to build the project package for distribution or deployment. ```bash npm run build ``` -------------------------------- ### Run Formatting Checks Source: https://github.com/ctrf-io/ctrf-js/blob/main/CONTRIBUTING.md Use this command to verify that your code formatting meets the project's requirements. ```bash npm run format:check ``` -------------------------------- ### Get Schema Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/functions/getSchema.md Retrieves the JSON Schema object for a specified version of the CTRF specification. ```APIDOC ## Function: getSchema() ### Description Retrieves the JSON Schema object for a specified version of the CTRF specification. ### Method N/A (This is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Function Parameters - **version** (string) - Required - The spec version (MAJOR.MINOR.PATCH) to get the schema for. ### Request Example ```typescript const v0_0Schema = getSchema('0.0.0'); const v1_0Schema = getSchema('1.0.0'); ``` ### Response #### Success Response (object) - **schema** (object) - The JSON Schema object for that version. #### Response Example ```json { "type": "object", "properties": { "exampleField": { "type": "string" } } } ``` ### Error Handling - **SchemaVersionError**: Thrown if the specified version is not supported. ``` -------------------------------- ### Run Tests Source: https://github.com/ctrf-io/ctrf-js/blob/main/CONTRIBUTING.md Execute this command to run the project's test suite and ensure code stability. ```bash npm test ``` -------------------------------- ### build() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Build and return the Test object. Throws BuilderError if required fields are missing. ```APIDOC ## build() ### Description Build and return the Test object. Throws BuilderError if required fields are missing. ### Method build ### Returns Test - The constructed Test object. ### Throws BuilderError - If required fields are missing. ``` -------------------------------- ### Calculate Summary Statistics Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Calculate summary statistics from an array of tests. Optionally override the start and stop timestamps. ```typescript import { calculateSummary } from 'ctrf' const summary = calculateSummary(tests) // With timing overrides const summary = calculateSummary(tests, { start: 1704067200000, stop: 1704067260000, }) ``` -------------------------------- ### Get Supported Spec Versions Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Returns a read-only array of all CTRF specification versions that are currently supported by the library. ```typescript function getSupportedSpecVersions(): readonly string[] ``` -------------------------------- ### Run Linting Checks Source: https://github.com/ctrf-io/ctrf-js/blob/main/CONTRIBUTING.md Execute this command to ensure your code adheres to the project's linting standards. ```bash npm run lint:check ``` -------------------------------- ### Parse JSON String Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/functions/parse.md Use this snippet to parse a JSON string into a CTRFReport object. No special setup is required. ```typescript const report = parse(jsonString); ``` -------------------------------- ### Get CTRF Schema Source: https://github.com/ctrf-io/ctrf-js/blob/main/src/README.md Retrieve the JSON Schema used by CTRF for validation. This is useful for understanding the structure of CTRF reports. ```typescript import { ctrf } from 'ctrf' // Get the JSON Schema const schema = ctrf.getSchema() ``` -------------------------------- ### Get CTRF Schema Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Retrieves the JSON Schema for a specified CTRF specification version. Throws a SchemaVersionError if the requested version is not supported. ```typescript function getSchema(version: string): object ``` ```typescript import { getSchema } from 'ctrf' const schema = getSchema('0.0.0') ``` -------------------------------- ### suite() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets the suite hierarchy for the test. ```APIDOC ## suite() ### Description Set the suite hierarchy. ### Parameters #### suites (`string[]`) - Optional: No - Description: An array of strings representing the suite hierarchy. ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### build() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/ReportBuilder.md Builds and returns the final CTRF report object. Throws an error if required fields are missing. ```APIDOC ## build(): CTRFReport ### Description Build and return the CTRF report. ### Returns - `CTRFReport` - The constructed CTRF report object. ### Throws - `BuilderError` - If required fields are missing from the report configuration. ``` -------------------------------- ### trace() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets the stack trace for the test. ```APIDOC ## trace() ### Description Set the stack trace. ### Parameters #### trace (`string`) - Optional: No - Description: The stack trace of the error. ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### stdout() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Set the standard output lines for the test. ```APIDOC ## stdout() ### Description Set the standard output lines for the test. ### Method stdout ### Parameters #### lines - **lines** (string[]) - Required - An array of strings representing the stdout lines. ### Returns `this` ``` -------------------------------- ### Environment Interface Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Captures metadata about the environment in which the tests were executed, such as OS, build details, and repository information. ```typescript interface Environment { appName?: string appVersion?: string buildName?: string buildNumber?: string buildUrl?: string repositoryName?: string repositoryUrl?: string commit?: string branchName?: string osPlatform?: string osRelease?: string osVersion?: string testEnvironment?: string extra?: Record } ``` -------------------------------- ### screenshot() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Set the screenshot for the test in base64 format. ```APIDOC ## screenshot() ### Description Set the screenshot for the test in base64 format. ### Method screenshot ### Parameters #### base64 - **base64** (string) - Required - The base64 encoded screenshot. ### Returns `this` ``` -------------------------------- ### Access CTRF Schema and Version Information Source: https://github.com/ctrf-io/ctrf-js/blob/main/README.md Import and use functions to access the CTRF JSON schema, retrieve schema for a specific version, and get current/supported spec version details. ```typescript import { schema, getSchema, getCurrentSpecVersion, getSupportedSpecVersions } from 'ctrf' // Get the current JSON Schema console.log(schema) // Get schema for specific version const v0_0Schema = getSchema('0.0.0') // Get version info const version = getCurrentSpecVersion() // '0.0.0' const supported = getSupportedSpecVersions() // ['0.0.0'] ``` -------------------------------- ### parameters() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Set custom parameters for the test. ```APIDOC ## parameters() ### Description Set custom parameters for the test. ### Method parameters ### Parameters #### params - **params** (Record) - Required - An object containing key-value pairs for parameters. ### Returns `this` ``` -------------------------------- ### addStep() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Add a step to the test. ```APIDOC ## addStep() ### Description Add a step to the test. ### Method addStep ### Parameters #### step - **step** (Step) - Required - The step object. ### Returns `this` ``` -------------------------------- ### Filtering and Querying CTRF Reports Source: https://github.com/ctrf-io/ctrf-js/blob/main/src/README.md Demonstrates various utility functions for filtering and querying tests within a CTRF report, including getting tests by status, filtering by criteria, finding specific tests, grouping tests, and extracting unique values. ```typescript import { ctrf } from 'ctrf' // Get tests by status const failed = ctrf.getFailedTests(report) const passed = ctrf.getPassedTests(report) const skipped = ctrf.getSkippedTests(report) const flaky = ctrf.getFlakyTests(report) // Filter by criteria const filtered = ctrf.filterTests(report, { status: 'failed', suite: 'Authentication', tags: ['smoke'], }) // Find specific test const test = ctrf.findTest(report, { name: 'login test' }) const testById = ctrf.findTest(report, { id: 'test-uuid' }) // Group tests const bySuite = ctrf.groupBy(report.results.tests, 'suite') const byStatus = ctrf.groupBy(report.results.tests, 'status') // Get unique values const suites = ctrf.getUniqueSuites(report) const tags = ctrf.getUniqueTags(report) ``` -------------------------------- ### browser() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Set the browser name for the test. ```APIDOC ## browser() ### Description Set the browser name for the test. ### Method browser ### Parameters #### name - **name** (string) - Required - The browser name. ### Returns `this` ``` -------------------------------- ### Building Reports Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/README.md Classes for programmatically constructing CTRF reports and their components. ```APIDOC ## Building Reports ### Description Offers a fluent API for creating CTRF reports and test objects. ### Classes - **ReportBuilder**: Build complete CTRF reports. - **TestBuilder**: Build individual test objects. ``` -------------------------------- ### device() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Set the device name for the test. ```APIDOC ## device() ### Description Set the device name for the test. ### Method device ### Parameters #### name - **name** (string) - Required - The device name. ### Returns `this` ``` -------------------------------- ### getSupportedSpecVersions() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/functions/getSupportedSpecVersions.md Retrieves a list of all supported specification versions for CTRF. ```APIDOC ## getSupportedSpecVersions() ### Description Retrieves an array of strings, where each string represents a supported specification version. ### Method GET ### Endpoint /ctrf-js/schema ### Returns #### Success Response (200) - **versions** (string[]) - An array of supported specification version strings. ### Response Example ```json { "versions": [ "1.0.0", "1.1.0", "2.0.0" ] } ``` ``` -------------------------------- ### environment() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/ReportBuilder.md Sets the environment information for the report. This method is chainable. ```APIDOC ## environment(env: Environment) ### Description Set the environment information. ### Parameters #### env - **env** (Environment) - An object containing environment details. ### Returns - `this` - The ReportBuilder instance for chaining. ``` -------------------------------- ### ReportBuilder Constructor Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/ReportBuilder.md Initializes a new instance of the ReportBuilder class. Optionally accepts an object for initial configuration. ```APIDOC ## new ReportBuilder() ### Description Initializes a new instance of the ReportBuilder class. ### Parameters #### options - **options** (ReportBuilderOptions) - Optional - An object to configure the ReportBuilder instance. ### Returns - `ReportBuilder` - A new instance of the ReportBuilder. ``` -------------------------------- ### TestBuilder Constructor Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Initializes a new instance of the TestBuilder class. It can optionally accept TestBuilderOptions. ```APIDOC ## new TestBuilder() ### Description Initializes a new instance of the TestBuilder class. ### Parameters #### options? (`TestBuilderOptions`) - Optional: Yes - Description: Options to configure the TestBuilder. Defaults to an empty object. ### Returns - `TestBuilder`: The newly created TestBuilder instance. ``` -------------------------------- ### Options Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/globals.md Configuration options for various CTRF operations. ```APIDOC ## Options ### Description Configuration objects used to customize the behavior of CTRF SDK functions. ### Interfaces - **SummaryOptions**: Options for calculating summary statistics. - **ParseOptions**: Options for parsing CTRF reports. - **StringifyOptions**: Options for serializing CTRF reports. - **ReportBuilderOptions**: Options for the ReportBuilder. - **TestBuilderOptions**: Options for the TestBuilder. - **FilterCriteria**: Criteria for filtering tests. - **InsightsOptions**: Options for generating insights. - **MergeOptions**: Options for merging reports. - **ValidateOptions**: Options for validating reports. - **ValidationResult**: Result of a validation operation. - **ValidationErrorDetail**: Detailed information about a validation error. ``` -------------------------------- ### tags() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets tags for the test. ```APIDOC ## tags() ### Description Set tags. ### Parameters #### tags (`string[]`) - Optional: No - Description: An array of tags for the test. ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### Replace Previous Results Storage with Manual File Writing Source: https://github.com/ctrf-io/ctrf-js/blob/main/MIGRATION.md The `storePreviousResults` function has been removed. Implement custom storage logic using file system operations and the `stringify` utility. ```typescript // ❌ OLD (v0.0.17) import { storePreviousResults } from 'ctrf' await storePreviousResults(report, './history') ``` ```typescript // ✅ NEW (v0.1.0) - Implement your own storage import { stringify } from 'ctrf' import { writeFileSync } from 'fs' const timestamp = Date.now() writeFileSync( `./history/report-${timestamp}.json`, stringify(report, { pretty: true }) ) ``` -------------------------------- ### extra() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Set extra metadata for the test. ```APIDOC ## extra() ### Description Set extra metadata for the test. ### Method extra ### Parameters #### data - **data** (Record) - Required - An object containing key-value pairs for extra metadata. ### Returns `this` ``` -------------------------------- ### Tool Interface Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Contains information about the test tool used to generate the report, including its name and version. ```typescript interface Tool { name: string version?: string extra?: Record } ``` -------------------------------- ### rawStatus() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets the raw status from the test framework. ```APIDOC ## rawStatus() ### Description Set the raw status from the test framework. ### Parameters #### status (`string`) - Optional: No - Description: The raw status string from the test framework. ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### Baseline Interface Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/interfaces/Baseline.md This interface represents a baseline report, which is used for comparison purposes. It includes essential details like the report ID and optional metadata such as timestamps, build information, and source descriptions. ```APIDOC ## Interface: Baseline Defined in: [types.ts:350](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L350) Reference to a baseline report ### Properties - **reportId** (`string`): Report ID of the baseline report. (Required) - **timestamp?** (`string`): Timestamp of the baseline report. (Optional) - **source?** (`string`): Source description (e.g., 'main-branch', 'previous-run'). (Optional) - **buildNumber?** (`number`): Build number of the baseline. (Optional) - **buildName?** (`string`): Build name of the baseline. (Optional) - **buildUrl?** (`string`): Build URL of the baseline. (Optional) - **commit?** (`string`): Git commit of the baseline. (Optional) - **extra?** (`Record`): Custom metadata. (Optional) ``` -------------------------------- ### Initialize ReportBuilder Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Use ReportBuilder to construct CTRF reports programmatically. Options can auto-generate IDs and timestamps. ```typescript class ReportBuilder { constructor(options?: ReportBuilderOptions) specVersion(version: string): this reportId(uuid?: string): this timestamp(date?: Date | string): this generatedBy(name: string): this tool(tool: Tool): this environment(env: Environment): this addTest(test: Test): this addTests(tests: Test[]): this insights(insights: Insights): this baseline(baseline: Baseline): this extra(data: Record): this summaryOverrides(overrides: Partial): this build(): CTRFReport } ``` -------------------------------- ### Create Reports and Tests with Builder Pattern Source: https://github.com/ctrf-io/ctrf-js/blob/main/MIGRATION.md Use the `ReportBuilder` and `TestBuilder` classes for a fluent and type-safe API to construct reports and tests. The `build()` method finalizes the object. ```typescript import { ReportBuilder, TestBuilder } from 'ctrf' const report = new ReportBuilder() .tool({ name: 'vitest', version: '1.0.0' }) .environment({ os: 'linux', arch: 'x64' }) .addTest( new TestBuilder() .name('User login test') .status('passed') .duration(1500) .suite(['Authentication', 'Login']) .tags(['smoke', 'critical']) .browser('chrome') .build() ) .addTests([test1, test2, test3]) // Batch add .build() ``` -------------------------------- ### tool() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/ReportBuilder.md Sets the information about the tool used to generate the report. This method is chainable. ```APIDOC ## tool(tool: Tool) ### Description Set the tool information. ### Parameters #### tool - **tool** (Tool) - An object containing information about the tool. ### Returns - `this` - The ReportBuilder instance for chaining. ``` -------------------------------- ### Report Building API Source: https://github.com/ctrf-io/ctrf-js/blob/main/API.md Enables programmatic construction of CTRF reports using a fluent API. ```APIDOC ## Report Building API ### Description Fluent API for constructing CTRF reports programmatically. ### Classes - **ReportBuilder**: Build complete CTRF reports. - **TestBuilder**: Build individual test objects. ``` -------------------------------- ### Error Handling Source: https://github.com/ctrf-io/ctrf-js/blob/main/src/README.md Information on how to handle potential errors during file reading, parsing, and schema validation. ```APIDOC ## Error Handling ### Description This section details the custom error types thrown by the CTRF library and how to handle them. ### Error Types - `ctrf.FileError`: Thrown when there are issues reading files (e.g., file not found). - `path` (string): The path to the file that caused the error. - `ctrf.ParseError`: Thrown when there are issues parsing JSON content. - `message` (string): A description of the parsing error. - `ctrf.ValidationError`: Thrown when the report data fails schema validation. - `errors` (array): An array of validation errors. ### Usage Example ```typescript try { const report = await ctrf.readReport('./missing.json'); } catch (error) { if (error instanceof ctrf.FileError) { console.error('File not found:', error.path); } else if (error instanceof ctrf.ParseError) { console.error('Invalid JSON:', error.message); } else if (error instanceof ctrf.ValidationError) { console.error('Schema validation failed:', error.errors); } } ``` ``` -------------------------------- ### baseline() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/ReportBuilder.md Sets the baseline reference for the report. This method is chainable. ```APIDOC ## baseline(baseline: Baseline) ### Description Set the baseline reference. ### Parameters #### baseline - **baseline** (Baseline) - An object representing the baseline reference. ### Returns - `this` - The ReportBuilder instance for chaining. ``` -------------------------------- ### name() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets the name of the test. ```APIDOC ## name() ### Description Set the test name. ### Parameters #### name (`string`) - Optional: No - Description: The name of the test. ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### status() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets the status of the test. ```APIDOC ## status() ### Description Set the test status. ### Parameters #### status (`TestStatus`) - Optional: No - Description: The status of the test (e.g., 'passed', 'failed'). ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### Access Schema Information Source: https://github.com/ctrf-io/ctrf-js/blob/main/MIGRATION.md Retrieve the current schema, specific schema versions using `getSchema`, the current spec version with `getCurrentSpecVersion`, and supported spec versions with `getSupportedSpecVersions`. ```typescript import { schema, getSchema, getCurrentSpecVersion, getSupportedSpecVersions, } from 'ctrf' console.log(schema) // Current version schema const oldSchema = getSchema('0.0.0') console.log(getCurrentSpecVersion()) // '0.0' console.log(getSupportedSpecVersions()) // ['0.0'] ``` -------------------------------- ### Attachment Interface Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/interfaces/Attachment.md Defines the structure for file attachments. ```APIDOC ## Interface: Attachment Defined in: [types.ts:214](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L214) File attachment ### Properties #### name > **name**: `string` Defined in: [types.ts:216](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L216) Attachment name *** #### contentType > **contentType**: `string` Defined in: [types.ts:218](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L218) MIME content type *** #### path > **path**: `string` Defined in: [types.ts:220](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L220) Path to the attachment file *** #### extra? > `optional` **extra?**: `Record` < `string`, `unknown` > Defined in: [types.ts:222](https://github.com/ctrf-io/ctrf-js/blob/main/src/types.ts#L222) Custom metadata ``` -------------------------------- ### Create a Test Result Object Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Instantiate TestBuilder and chain methods to set test properties like name, status, duration, and suite. Finally, call build() to create the test object. ```typescript const test = new TestBuilder() .name('should add numbers') .status('passed') .duration(150) .suite(['math', 'addition']) .build(); ``` -------------------------------- ### Import and Use CTRF Constants Source: https://github.com/ctrf-io/ctrf-js/blob/main/README.md Import and utilize predefined constants from the 'ctrf' library for report formats, spec versions, test statuses, and namespaces. ```typescript import { REPORT_FORMAT, CURRENT_SPEC_VERSION, SUPPORTED_SPEC_VERSIONS, TEST_STATUSES, CTRF_NAMESPACE, } from 'ctrf' REPORT_FORMAT // 'CTRF' CURRENT_SPEC_VERSION // '0.0.0' SUPPORTED_SPEC_VERSIONS // ['0.0.0'] TEST_STATUSES // ['passed', 'failed', 'skipped', 'pending', 'other'] CTRF_NAMESPACE // UUID namespace for deterministic IDs ``` -------------------------------- ### Summary Interface Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Provides aggregated statistics for test runs, such as counts of passed, failed, and skipped tests, along with timing information. ```typescript interface Summary { tests: number passed: number failed: number skipped: number pending: number other: number flaky?: number suites?: number start: number stop: number duration?: number extra?: Record } ``` -------------------------------- ### filePath() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets the file path where the test is located. ```APIDOC ## filePath() ### Description Set file path. ### Parameters #### path (`string`) - Optional: No - Description: The path to the file containing the test. ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### CTRF Report Building API Source: https://github.com/ctrf-io/ctrf-js/blob/main/README.md Utilizes fluent APIs for constructing CTRF reports and individual test objects. `ReportBuilder` allows for chaining methods to add tools, environments, and tests, while `TestBuilder` facilitates the creation of detailed test objects. ```APIDOC ## CTRF Report Building API ### Description Utilizes fluent APIs for constructing CTRF reports and individual test objects. `ReportBuilder` allows for chaining methods to add tools, environments, and tests, while `TestBuilder` facilitates the creation of detailed test objects. ### Imports ```typescript import { ReportBuilder, TestBuilder } from 'ctrf' ``` ### `ReportBuilder` Used to construct a CTRF report. #### Methods - **`tool(toolInfo: Tool): ReportBuilder`**: Adds information about the testing tool used. - **`environment(envInfo: Environment): ReportBuilder`**: Adds information about the execution environment. - **`addTest(test: Test): ReportBuilder`**: Adds a test object to the report. - **`build(): CTRFReport`**: Finalizes the report construction and returns the `CTRFReport` object. ### `TestBuilder` Used to construct an individual test object. #### Methods - **`name(name: string): TestBuilder`**: Sets the name of the test. - **`status(status: TestStatus): TestBuilder`**: Sets the status of the test (e.g., 'passed', 'failed', 'skipped'). - **`duration(duration: number): TestBuilder`**: Sets the execution duration of the test in milliseconds. - **`suite(suite: string[]): TestBuilder`**: Sets the test suite hierarchy. - **`tags(tags: string[]): TestBuilder`**: Sets the tags associated with the test. - **`filePath(filePath: string): TestBuilder`**: Sets the path to the test file. - **`browser(browser: string): TestBuilder`**: Sets the browser used for the test, if applicable. - **`message(message: string): TestBuilder`**: Sets a message associated with the test result (e.g., error message). - **`build(): Test`**: Finalizes the test construction and returns the `Test` object. ### Usage Examples **Building a Report:** ```typescript const report = new ReportBuilder() .tool({ name: 'vitest', version: '1.0.0' }) .environment({ os: 'linux', arch: 'x64' }) .addTest(/* ... */) .build() ``` **Building a Test:** ```typescript const test = new TestBuilder() .name('User login test') .status('passed') .duration(1500) .suite(['Authentication', 'Login']) .tags(['smoke', 'critical']) .filePath('tests/auth/login.test.ts') .browser('chrome') .build() ``` ``` -------------------------------- ### ai() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/TestBuilder.md Sets AI-generated analysis for the test. ```APIDOC ## ai() ### Description Set AI-generated analysis. ### Parameters #### analysis (`string`) - Optional: No - Description: AI-generated analysis of the test. ### Returns - `this`: The TestBuilder instance for chaining. ``` -------------------------------- ### calculateSummary() Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/functions/calculateSummary.md Calculates a summary object from an array of test results. It can optionally accept timing information to include in the summary. ```APIDOC ## Function: calculateSummary() > **calculateSummary**(`tests`, `options?`): [`Summary`] Defined in: [summary.ts:27](https://github.com/ctrf-io/ctrf-js/blob/main/src/summary.ts#L27) ## Parameters ### tests [`Test`][] Array of test results ### options? [`SummaryOptions`] = `{}` Optional timing information ## Returns [`Summary`] Calculated summary object ## Example ```typescript const summary = calculateSummary(tests); // With timing const summary = calculateSummary(tests, { start: 1704067200000, stop: 1704067260000 }); ``` ``` -------------------------------- ### Accessing Schema Definition Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/variables/schema.md Import and access the schema object to retrieve its properties, such as the schema version. ```typescript import { schema } from 'ctrf'; console.log(schema.$schema); ``` -------------------------------- ### Schema & Versioning API Source: https://github.com/ctrf-io/ctrf-js/blob/main/API.md APIs for retrieving and managing CTRF schema versions. ```APIDOC ## Schema & Versioning API ### Description APIs for retrieving and managing CTRF schema versions. ### Functions - **getSchema**: Get JSON Schema for a spec version. - **getCurrentSpecVersion**: Get current version. - **getSupportedSpecVersions**: List supported versions. ### Variables - **schema**: Current schema object. ``` -------------------------------- ### Initialize TestBuilder Source: https://github.com/ctrf-io/ctrf-js/blob/main/website/reference.md Use TestBuilder to construct individual Test objects. An option is available to auto-generate test UUIDs. ```typescript class TestBuilder { constructor(options?: TestBuilderOptions) id(uuid?: string): this name(name: string): this status(status: TestStatus): this duration(ms: number): this start(timestamp: number): this stop(timestamp: number): this suite(suite: string[]): this message(message: string): this trace(trace: string): this snippet(snippet: string): this ai(ai: string): this line(line: number): this rawStatus(rawStatus: string): this tags(tags: string[]): this type(type: string): this filePath(filePath: string): this retries(retries: number): this addRetryAttempt(attempt: RetryAttempt): this flaky(flaky: boolean): this stdout(stdout: string[]): this stderr(stderr: string[]): this threadId(threadId: string): this browser(browser: string): this device(device: string): this screenshot(screenshot: string): this parameters(params: Record): this addStep(step: Step): this addAttachment(attachment: Attachment): this extra(data: Record): this build(): Test } ``` -------------------------------- ### SchemaVersionError Class Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/classes/SchemaVersionError.md Details about the SchemaVersionError class, including its constructor and properties. ```APIDOC ## Class: SchemaVersionError Defined in: [errors.ts:61](https://github.com/ctrf-io/ctrf-js/blob/main/src/errors.ts#L61) ### Description Represents an error when a schema version is not supported. ### Extends - [`CTRFError`](CTRFError.md) ### Constructors #### Constructor > **new SchemaVersionError**(`version`, `supportedVersions`): `SchemaVersionError` Defined in: [errors.ts:67](https://github.com/ctrf-io/ctrf-js/blob/main/src/errors.ts#L67) #### Parameters ##### version - **version** (string) - The unsupported version string. ##### supportedVersions - **supportedVersions** (string[]) - An array of supported version strings. #### Returns - `SchemaVersionError` - An instance of SchemaVersionError. #### Overrides - [`CTRFError`](CTRFError.md).[`constructor`](CTRFError.md#constructor) ### Properties #### version > `readonly` **version**: `string` Defined in: [errors.ts:63](https://github.com/ctrf-io/ctrf-js/blob/main/src/errors.ts#L63) The unsupported version. #### supportedVersions > `readonly` **supportedVersions**: `string`[] Defined in: [errors.ts:65](https://github.com/ctrf-io/ctrf-js/blob/main/src/errors.ts#L65) Supported versions. ``` -------------------------------- ### Builders Source: https://github.com/ctrf-io/ctrf-js/blob/main/docs/globals.md Fluent builders for constructing CTRF reports and test objects. ```APIDOC ## Builders ### Description Provides fluent interfaces for creating CTRF reports and test objects. ### Classes - **ReportBuilder**: For constructing CTRF reports. - **TestBuilder**: For constructing Test objects. ``` -------------------------------- ### Adding Insights and Checking Flakiness Source: https://github.com/ctrf-io/ctrf-js/blob/main/README.md Enrich a CTRF report with historical insights and check if a specific test is flaky. ```typescript import { addInsights, isTestFlaky } from 'ctrf' // Enrich a report with insights from historical data const enriched = addInsights( currentReport, historicalReports, { baseline: baselineReport } ) // Access insights console.log(enriched.insights?.passRate) // { current: 0.95, baseline: 0.90, change: 0.05 } console.log(enriched.insights?.flakyRate) // { current: 0.02, baseline: 0.05, change: -0.03 } // Check if a test is flaky const isFlaky = isTestFlaky(test) ``` -------------------------------- ### Replace Tree/Suite Operations with Filtering Source: https://github.com/ctrf-io/ctrf-js/blob/main/MIGRATION.md Tree and suite organization functions like `organizeTestsBySuite`, `traverseTree`, `findSuiteByName`, `flattenTree`, `getAllTests`, and `getSuiteStats` have been removed. Use `filterTests` and custom reduce logic for similar functionality. ```typescript // ❌ OLD (v0.0.17) import { organizeTestsBySuite, traverseTree, findSuiteByName, flattenTree, getAllTests, getSuiteStats, } from 'ctrf' const tree = organizeTestsBySuite(report) traverseTree(tree, node => { /* ... */ }) const suite = findSuiteByName(tree, 'unit') const tests = getAllTests(tree) ``` ```typescript // ✅ NEW (v0.1.0) - Use filter and custom logic import { filterTests } from 'ctrf' // Get tests by suite const unitTests = filterTests(report, { suite: ['unit'] }) // Group tests by suite manually const testsBySuite = report.results.tests.reduce( (acc, test) => { const suiteKey = test.suite?.join('/') || 'root' if (!acc[suiteKey]) acc[suiteKey] = [] acc[suiteKey].push(test) return acc }, {} as Record // Assuming Test type is defined elsewhere ) ```