All files / tooling/src/testing test-renderer.js

33.78% Statements 25/74
18.75% Branches 6/32
29.62% Functions 8/27
34.24% Lines 25/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366                          8x                 14x 14x 14x 14x                     6x 6x   6x 1x     5x                           1x 1x   1x                                                                                             2x 2x 2x   2x 1x     1x                           1x 1x   1x                                                                                                                           1x                                                                   14x 14x                                                                                                                                                                                                                                                                                
/**
 * Coherent.js Test Renderer
 * 
 * Provides utilities for rendering and testing Coherent.js components
 * in a test environment.
 * 
 * @module testing/test-renderer
 */
 
import { render } from '@coherent.js/core';
 
/** Escape a string for literal use inside a RegExp. */
function escapeRegExp(text) {
  return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
 
/**
 * Test renderer result
 * Provides methods to query and interact with rendered components
 */
export class TestRendererResult {
  constructor(component, html, container = null) {
    this.component = component;
    this.html = html;
    this.container = container;
    this.queries = new Map();
  }
 
  /**
   * Get element by test ID
   * @param {string} testId - Test ID to search for
   * @returns {Object|null} Element or null
   */
  getByTestId(testId) {
    // Capture from the start of the opening tag, so the match's `html`
    // carries the element's tag name and all of its attributes.
    const regex = new RegExp(`<[a-zA-Z][\\w:-]*(?:\\s[^>]*?)?\\sdata-testid="${escapeRegExp(testId)}"[^>]*>([^<]*)<`, 'i');
    const match = this.html.match(regex);
    
    if (!match) {
      throw new Error(`Unable to find element with testId: ${testId}`);
    }
    
    return {
      text: match[1],
      html: match[0],
      testId,
      exists: true
    };
  }
 
  /**
   * Query element by test ID (returns null if not found)
   * @param {string} testId - Test ID to search for
   * @returns {Object|null} Element or null
   */
  queryByTestId(testId) {
    try {
      return this.getByTestId(testId);
    } catch {
      return null;
    }
  }
 
  /**
   * Get element by text content
   * @param {string|RegExp} text - Text to search for
   * @returns {Object} Element
   */
  getByText(text) {
    const regex = typeof text === 'string' 
      ? new RegExp(`>([^<]*${escapeRegExp(text)}[^<]*)<`, 'i')
      : new RegExp(`>([^<]*)<`, 'i');
    
    const match = this.html.match(regex);
    
    if (!match || (typeof text === 'string' && !match[1].includes(text))) {
      throw new Error(`Unable to find element with text: ${text}`);
    }
    
    return {
      text: match[1],
      html: match[0],
      exists: true
    };
  }
 
  /**
   * Query element by text (returns null if not found)
   * @param {string|RegExp} text - Text to search for
   * @returns {Object|null} Element or null
   */
  queryByText(text) {
    try {
      return this.getByText(text);
    } catch {
      return null;
    }
  }
 
  /**
   * Get element by class name
   * @param {string} className - Class name to search for
   * @returns {Object} Element
   */
  getByClassName(className) {
    // Whole class tokens: 'btn' matches class="btn primary", not "btn-primary".
    const token = escapeRegExp(className);
    const regex = new RegExp(`<[a-zA-Z][\\w:-]*(?:\\s[^>]*?)?\\sclass="(?:[^"]*\\s)?${token}(?:\\s[^"]*)?"[^>]*>([^<]*)<`, 'i');
    const match = this.html.match(regex);
    
    if (!match) {
      throw new Error(`Unable to find element with className: ${className}`);
    }
    
    return {
      text: match[1],
      html: match[0],
      className,
      exists: true
    };
  }
 
  /**
   * Query element by class name (returns null if not found)
   * @param {string} className - Class name to search for
   * @returns {Object|null} Element or null
   */
  queryByClassName(className) {
    try {
      return this.getByClassName(className);
    } catch {
      return null;
    }
  }
 
  /**
   * Get all elements by tag name
   * @param {string} tagName - Tag name to search for
   * @returns {Array<Object>} Array of elements
   */
  getAllByTagName(tagName) {
    const tag = escapeRegExp(tagName);
    const regex = new RegExp(`<${tag}(?=[\\s/>])[^>]*>([^<]*)</${tag}>`, 'gi');
    const matches = [...this.html.matchAll(regex)];
    
    return matches.map(match => ({
      text: match[1],
      html: match[0],
      tagName,
      exists: true
    }));
  }
 
  /**
   * Check if element exists
   * @param {string} selector - Selector (testId, text, className)
   * @param {string} type - Type of selector ('testId', 'text', 'className')
   * @returns {boolean} True if exists
   */
  exists(selector, type = 'testId') {
    switch (type) {
      case 'testId':
        return this.queryByTestId(selector) !== null;
      case 'text':
        return this.queryByText(selector) !== null;
      case 'className':
        return this.queryByClassName(selector) !== null;
      default:
        return false;
    }
  }
 
  /**
   * Get the rendered HTML
   * @returns {string} HTML string
   */
  getHTML() {
    return this.html;
  }
 
  /**
   * Get the component
   * @returns {Object} Component object
   */
  getComponent() {
    return this.component;
  }
 
  /**
   * Create a snapshot of the rendered output
   * @returns {string} Formatted HTML for snapshot testing
   */
  toSnapshot() {
    return this.html
      .replace(/>\s+</g, '><') // Remove whitespace between tags
      .trim();
  }
 
  /**
   * Debug: print the rendered HTML
   */
  debug() {
    console.log('=== Rendered HTML ===');
    console.log(this.html);
    console.log('=== Component ===');
    console.log(JSON.stringify(this.component, null, 2));
  }
}
 
/**
 * Render a component for testing
 * 
 * @param {Object} component - Component to render
 * @param {Object} [options] - Render options
 * @returns {TestRendererResult} Test renderer result
 * 
 * @example
 * const { getByTestId } = renderComponent({
 *   div: {
 *     'data-testid': 'my-div',
 *     text: 'Hello World'
 *   }
 * });
 * 
 * expect(getByTestId('my-div').text).toBe('Hello World');
 */
export function renderComponent(component, options = {}) {
  const html = render(component, options);
  return new TestRendererResult(component, html);
}
 
/**
 * Render a component asynchronously
 * 
 * @param {Object|Function} component - Component or component factory
 * @param {Object} [props] - Component props
 * @param {Object} [options] - Render options
 * @returns {Promise<TestRendererResult>} Test renderer result
 */
export async function renderComponentAsync(component, props = {}, options = {}) {
  // If component is a function, call it with props
  const resolvedComponent = typeof component === 'function' 
    ? await component(props)
    : component;
  
  const html = render(resolvedComponent, options);
  return new TestRendererResult(resolvedComponent, html);
}
 
/**
 * Create a test renderer instance
 * Useful for testing component updates
 */
export class TestRenderer {
  constructor(component, options = {}) {
    this.component = component;
    this.options = options;
    this.result = null;
    this.renderCount = 0;
  }
 
  /**
   * Render the component
   * @returns {TestRendererResult} Render result
   */
  render() {
    this.renderCount++;
    const html = render(this.component, this.options);
    this.result = new TestRendererResult(this.component, html);
    return this.result;
  }
 
  /**
   * Update the component and re-render
   * @param {Object} newComponent - Updated component
   * @returns {TestRendererResult} Render result
   */
  update(newComponent) {
    this.component = newComponent;
    return this.render();
  }
 
  /**
   * Get the current result
   * @returns {TestRendererResult|null} Current result
   */
  getResult() {
    return this.result;
  }
 
  /**
   * Get render count
   * @returns {number} Number of renders
   */
  getRenderCount() {
    return this.renderCount;
  }
 
  /**
   * Unmount the component
   */
  unmount() {
    this.component = null;
    this.result = null;
  }
}
 
/**
 * Create a test renderer
 * 
 * @param {Object} component - Component to render
 * @param {Object} [options] - Render options
 * @returns {TestRenderer} Test renderer instance
 * 
 * @example
 * const renderer = createTestRenderer(MyComponent);
 * const result = renderer.render();
 * expect(result.getByText('Hello')).toBeTruthy();
 * 
 * // Update and re-render
 * renderer.update(UpdatedComponent);
 * expect(renderer.getRenderCount()).toBe(2);
 */
export function createTestRenderer(component, options = {}) {
  return new TestRenderer(component, options);
}
 
/**
 * Shallow render a component (only render top level)
 * 
 * @param {Object} component - Component to render
 * @returns {Object} Shallow rendered component
 */
export function shallowRender(component) {
  // Clone component without rendering children
  const shallow = { ...component };
  
  Object.keys(shallow).forEach(key => {
    if (shallow[key] && typeof shallow[key] === 'object') {
      if (shallow[key].children) {
        shallow[key] = {
          ...shallow[key],
          children: Array.isArray(shallow[key].children)
            ? shallow[key].children.map(() => ({ _shallow: true }))
            : { _shallow: true }
        };
      }
    }
  });
  
  return shallow;
}
 
/**
 * Export all testing utilities
 */
export default {
  renderComponent,
  renderComponentAsync,
  createTestRenderer,
  shallowRender,
  TestRenderer,
  TestRendererResult
};