OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-note / test / helpers / fixtures.js

116 lines · javascript ref:
/**
 * Test Fixtures and Helpers
 *
 * Common utilities for testing hypernote components
 */

// Mock registry for testing (in-memory Hyperbee-compatible)
export class MockRegistry {
  constructor() {
    this.data = new Map()
  }

  async get(key) {
    const value = this.data.get(key)
    return value ? { value } : null
  }

  async put(key, value) {
    this.data.set(key, value)
  }

  async del(key) {
    this.data.delete(key)
  }

  async * createReadStream(options = {}) {
    const { gt, gte, lt } = options
    const sorted = [...this.data.entries()].sort((a, b) => a[0].localeCompare(b[0]))
    for (const [key, value] of sorted) {
      if (gt && key <= gt) continue
      if (gte && key < gte) continue
      if (lt && key >= lt) continue
      yield { key, value }
    }
  }

  clear() {
    this.data.clear()
  }
}

// Mock corestore for testing
export class MockCorestore {
  constructor() {
    this.cores = new Map()
  }

  get(options = {}) {
    const name = options.name || 'default'
    if (!this.cores.has(name)) {
      this.cores.set(name, new MockCore())
    }
    return this.cores.get(name)
  }
}

// Mock hypercore for testing
export class MockCore {
  constructor() {
    this.data = []
    this.isReady = false
  }

  async ready() {
    this.isReady = true
  }

  async append(block) {
    this.data.push(block)
    return this.data.length - 1
  }

  async get(index) {
    return this.data[index]
  }

  get length() {
    return this.data.length
  }
}

// Utility: wait for a condition
export async function waitFor(condition, timeout = 5000, interval = 100) {
  const start = Date.now()
  while (Date.now() - start < timeout) {
    if (await condition()) return true
    await sleep(interval)
  }
  throw new Error('Timeout waiting for condition')
}

// Utility: sleep
export function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

// Utility: create a test context
export function createTestContext() {
  return {
    registry: new MockRegistry(),
    corestore: new MockCorestore(),
    cleanup: async function() {
      this.registry.clear()
    }
  }
}

export default {
  MockRegistry,
  MockCorestore,
  MockCore,
  waitFor,
  sleep,
  createTestContext
}