simpleQuotationLifecycle.test.mjs 2.01 KB
import assert from 'node:assert/strict'
import test from 'node:test'

import { bindSimpleQuotationCarSelection } from '../pages/carQuotation/services/simpleQuotationLifecycle.js'

class MemoryEventBus {
  constructor() {
    this.events = new Map()
  }

  on(eventName, handler) {
    const handlers = this.events.get(eventName) || []
    handlers.push(handler)
    this.events.set(eventName, handlers)
  }

  off(eventName, handler) {
    const handlers = this.events.get(eventName) || []
    this.events.set(
      eventName,
      handlers.filter(item => item !== handler)
    )
  }

  emit(eventName, payload) {
    for (const handler of [...(this.events.get(eventName) || [])]) {
      handler(payload)
    }
  }

  listenerCount(eventName) {
    return (this.events.get(eventName) || []).length
  }
}

test('IT-EQ-SIMPLE-LIFECYCLE-001: registers one car-selection handler and dispose removes that exact handler', () => {
  const eventBus = new MemoryEventBus()
  const patches = []

  const dispose = bindSimpleQuotationCarSelection(eventBus, patch => {
    patches.push(patch)
  })

  assert.equal(eventBus.listenerCount('set_car_info'), 1)

  eventBus.emit('set_car_info', {
    vehicleBrandId: 'brand-1',
    vehicleBrandName: '品牌甲',
    vehicleSubBrandId: 'sub-brand-1',
    vehicleSubBrandName: '子品牌甲',
    vehicleSeriesId: 'series-1',
    vehicleSeriesName: '车系甲'
  })
  assert.deepEqual(patches, [
    {
      'owner.carBrandId': 'brand-1',
      'owner.carBrand': '品牌甲',
      'owner.carChildsBrandId': 'sub-brand-1',
      'owner.carChildsBrandName': '子品牌甲',
      'owner.carSeriesId': 'series-1',
      'owner.carSeriesName': '车系甲'
    }
  ])

  dispose()
  assert.equal(eventBus.listenerCount('set_car_info'), 0)

  eventBus.emit('set_car_info', {
    vehicleBrandId: 'brand-2',
    vehicleBrandName: '品牌乙',
    vehicleSubBrandId: 'sub-brand-2',
    vehicleSubBrandName: '子品牌乙',
    vehicleSeriesId: 'series-2',
    vehicleSeriesName: '车系乙'
  })
  assert.equal(patches.length, 1)
})