All files / testing/src test-utils.js

62.04% Statements 85/137
52.5% Branches 21/40
58.92% Functions 33/56
61.11% Lines 77/126

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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398                                8x 1x       7x                   7x 7x 5x     7x           1x 1x   1x 1x   1x 1x   1x     1x 1x   1x     1x 1x   1x                               3x   3x 3x   3x 25x 25x 2x 2x           23x 1x 1x     22x     3x                                                                                                               8x 8x   8x 8x         8x 8x 8x             8x       8x           8x 1x 1x     8x         8x         8x 3x 2x     8x 1x 1x     8x         8x                     3x 3x   3x   3x 1x     3x                                       2x 1x 1x 1x 1x 1x 1x               1x       1x       1x         1x         1x         1x         1x         1x                             1x                                                                                                                                                              
/**
 * Coherent.js Test Utilities
 * 
 * Helper functions for testing Coherent.js components
 * 
 * @module testing/test-utils
 */
 
/**
 * Simulate an event on an element
 * 
 * @param {Object} element - Element to fire event on
 * @param {string} eventType - Type of event (click, change, etc.)
 * @param {Object} [eventData] - Additional event data
 */
export function fireEvent(element, eventType, eventData = {}) {
  if (!element) {
    throw new Error('Element is required for fireEvent');
  }
  
  // In a test environment, we simulate the event
  const event = {
    type: eventType,
    target: element,
    currentTarget: element,
    preventDefault: () => {},
    stopPropagation: () => {},
    ...eventData
  };
  
  // If element has an event handler, call it
  const handlerName = `on${eventType}`;
  if (element[handlerName] && typeof element[handlerName] === 'function') {
    element[handlerName](event);
  }
  
  return event;
}
 
/**
 * Common event helpers
 */
export const fireEvent_click = (element, eventData) => 
  fireEvent(element, 'click', eventData);
 
export const fireEvent_change = (element, value) => 
  fireEvent(element, 'change', { target: { value } });
 
export const fireEvent_input = (element, value) => 
  fireEvent(element, 'input', { target: { value } });
 
export const fireEvent_submit = (element, eventData) => 
  fireEvent(element, 'submit', eventData);
 
export const fireEvent_keyDown = (element, key) => 
  fireEvent(element, 'keydown', { key });
 
export const fireEvent_keyUp = (element, key) => 
  fireEvent(element, 'keyup', { key });
 
export const fireEvent_focus = (element) => 
  fireEvent(element, 'focus');
 
export const fireEvent_blur = (element) => 
  fireEvent(element, 'blur');
 
/**
 * Wait for a condition to be true
 * 
 * @param {Function} condition - Condition function
 * @param {Object} [options] - Wait options
 * @param {number} [options.timeout=1000] - Timeout in ms
 * @param {number} [options.interval=50] - Check interval in ms
 * @returns {Promise<void>}
 * 
 * @example
 * await waitFor(() => getByText('Loaded').exists, { timeout: 2000 });
 */
export function waitFor(condition, options = {}) {
  const { timeout = 1000, interval = 50 } = options;
  
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    
    const check = () => {
      try {
        if (condition()) {
          resolve();
          return;
        }
      } catch {
        // Condition threw an error, keep waiting
      }
      
      if (Date.now() - startTime >= timeout) {
        reject(new Error(`Timeout waiting for condition after ${timeout}ms`));
        return;
      }
      
      setTimeout(check, interval);
    };
    
    check();
  });
}
 
/**
 * Wait for element to appear
 * 
 * @param {Function} queryFn - Query function that returns element
 * @param {Object} [options] - Wait options
 * @returns {Promise<Object>} Element
 */
export async function waitForElement(queryFn, options = {}) {
  let element = null;
  
  await waitFor(() => {
    element = queryFn();
    return element !== null;
  }, options);
  
  return element;
}
 
/**
 * Wait for element to disappear
 * 
 * @param {Function} queryFn - Query function that returns element
 * @param {Object} [options] - Wait options
 * @returns {Promise<void>}
 */
export async function waitForElementToBeRemoved(queryFn, options = {}) {
  await waitFor(() => {
    const element = queryFn();
    return element === null;
  }, options);
}
 
/**
 * Act utility for batching updates
 * Useful for testing state changes
 * 
 * @param {Function} callback - Callback to execute
 * @returns {Promise<void>}
 */
export async function act(callback) {
  await callback();
  // Allow any pending updates to flush
  await new Promise(resolve => setTimeout(resolve, 0));
}
 
/**
 * Create a mock function
 * 
 * @param {Function} [implementation] - Optional implementation
 * @returns {Function} Mock function
 */
export function createMock(implementation) {
  const calls = [];
  const results = [];
  
  const mockFn = function(...args) {
    calls.push(args);
    
    let result;
    let error;
    
    try {
      result = implementation ? implementation(...args) : undefined;
      results.push({ type: 'return', value: result });
    } catch (err) {
      error = err;
      results.push({ type: 'throw', value: error });
      throw error;
    }
    
    return result;
  };
  
  // Add mock utilities
  mockFn.mock = {
    calls,
    results,
    instances: []
  };
  
  mockFn.mockClear = () => {
    calls.length = 0;
    results.length = 0;
  };
  
  mockFn.mockReset = () => {
    mockFn.mockClear();
    implementation = undefined;
  };
  
  mockFn.mockImplementation = (fn) => {
    implementation = fn;
    return mockFn;
  };
  
  mockFn.mockReturnValue = (value) => {
    implementation = () => value;
    return mockFn;
  };
  
  mockFn.mockResolvedValue = (value) => {
    implementation = () => Promise.resolve(value);
    return mockFn;
  };
  
  mockFn.mockRejectedValue = (error) => {
    implementation = () => Promise.reject(error);
    return mockFn;
  };
  
  return mockFn;
}
 
/**
 * Create a spy on an object method
 * 
 * @param {Object} object - Object to spy on
 * @param {string} method - Method name
 * @returns {Function} Spy function
 */
export function createSpy(object, method) {
  const original = object[method];
  const spy = createMock(original.bind(object));
  
  object[method] = spy;
  
  spy.mockRestore = () => {
    object[method] = original;
  };
  
  return spy;
}
 
/**
 * Cleanup utility
 * Cleans up after tests
 */
export function cleanup() {
  // Clear any timers
  // Reset any global state
  // This would be expanded based on framework needs
}
 
/**
 * Within utility - scopes queries to a container
 * 
 * @param {Object} container - Container result
 * @returns {Object} Scoped queries
 */
export function within(container) {
  return {
    getByTestId: (testId) => container.getByTestId(testId),
    queryByTestId: (testId) => container.queryByTestId(testId),
    getByText: (text) => container.getByText(text),
    queryByText: (text) => container.queryByText(text),
    getByClassName: (className) => container.getByClassName(className),
    queryByClassName: (className) => container.queryByClassName(className)
  };
}
 
/**
 * Screen utility - global queries
 * Useful for accessing rendered content without storing result
 */
export const screen = {
  _result: null,
  
  setResult(result) {
    this._result = result;
  },
  
  getByTestId(testId) {
    Eif (!this._result) throw new Error('No component rendered');
    return this._result.getByTestId(testId);
  },
  
  queryByTestId(testId) {
    Eif (!this._result) return null;
    return this._result.queryByTestId(testId);
  },
  
  getByText(text) {
    Eif (!this._result) throw new Error('No component rendered');
    return this._result.getByText(text);
  },
  
  queryByText(text) {
    Eif (!this._result) return null;
    return this._result.queryByText(text);
  },
  
  getByClassName(className) {
    Eif (!this._result) throw new Error('No component rendered');
    return this._result.getByClassName(className);
  },
  
  queryByClassName(className) {
    Eif (!this._result) return null;
    return this._result.queryByClassName(className);
  },
  
  debug() {
    if (this._result) {
      this._result.debug();
    }
  }
};
 
/**
 * User event simulation
 * More realistic event simulation than fireEvent
 */
export const userEvent = {
  /**
   * Simulate user typing
   */
  type: async (element, text, options = {}) => {
    const { delay = 0 } = options;
    
    for (const char of text) {
      fireEvent_keyDown(element, char);
      fireEvent_input(element, element.value + char);
      fireEvent_keyUp(element, char);
      
      if (delay > 0) {
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  },
  
  /**
   * Simulate user click
   */
  click: async (element) => {
    fireEvent_focus(element);
    fireEvent_click(element);
  },
  
  /**
   * Simulate user double click
   */
  dblClick: async (element) => {
    await userEvent.click(element);
    await userEvent.click(element);
  },
  
  /**
   * Simulate user clearing input
   */
  clear: async (element) => {
    fireEvent_input(element, '');
    fireEvent_change(element, '');
  },
  
  /**
   * Simulate user selecting option
   */
  selectOptions: async (element, values) => {
    const valueArray = Array.isArray(values) ? values : [values];
    fireEvent_change(element, valueArray[0]);
  },
  
  /**
   * Simulate user tab navigation
   */
  tab: async () => {
    // Simulate tab key
    const activeElement = document.activeElement;
    if (activeElement) {
      fireEvent_keyDown(activeElement, 'Tab');
      fireEvent_blur(activeElement);
    }
  }
};
 
/**
 * Export all utilities
 */
export default {
  fireEvent,
  waitFor,
  waitForElement,
  waitForElementToBeRemoved,
  act,
  createMock,
  createSpy,
  cleanup,
  within,
  screen,
  userEvent
};