submitWorkflow.test.mjs 5.19 KB
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
  buildSubmitUiResult,
  resolveBoutiqueSubmitAction,
  runWithSubmitLock,
  runValidationPipeline,
  submitBoutiqueOrder
} from '../services/submitWorkflow.js'

describe('boutique submit workflow', () => {
  it('runs validators in order and stops at the first failure', async () => {
    const calls = []
    const result = await runValidationPipeline([
      async () => {
        calls.push('daily')
        return { isValid: true }
      },
      () => {
        calls.push('goods')
        return {
          isValid: false,
          message: '商品错误',
          errorKey: 'goods',
          presentation: 'toast'
        }
      },
      () => {
        calls.push('vin')
        return { isValid: true }
      }
    ])
    assert.deepEqual(calls, ['daily', 'goods'])
    assert.deepEqual(result, {
      ok: false,
      message: '商品错误',
      errorKey: 'goods',
      presentation: 'toast'
    })
  })

  it('keeps modal as the default presentation for other validation messages', async () => {
    assert.deepEqual(
      await runValidationPipeline([
        () => ({ isValid: false, message: '订单金额格式不正确' })
      ]),
      {
        ok: false,
        message: '订单金额格式不正确',
        errorKey: null,
        presentation: null
      }
    )
  })

  it('propagates synchronous throws and asynchronous rejects to the page boundary', async () => {
    await assert.rejects(
      runValidationPipeline([() => { throw new Error('sync') }]),
      /sync/
    )
    await assert.rejects(
      runValidationPipeline([async () => { throw new Error('async') }]),
      /async/
    )
  })

  it('selects all five existing submit modes without changing API names', () => {
    assert.deepEqual(resolveBoutiqueSubmitAction({}), {
      method: 'createWithPay',
      mode: 'normal'
    })
    assert.deepEqual(resolveBoutiqueSubmitAction({ save: true }), {
      method: 'createPrerecordedOrder',
      mode: 'prerecorded'
    })
    assert.deepEqual(resolveBoutiqueSubmitAction({ isErrorOrder: true }), {
      method: 'correctionOrder',
      mode: 'correction'
    })
    assert.deepEqual(
      resolveBoutiqueSubmitAction({ orderCreateType: 'additionRecordOrder' }),
      { method: 'supplementOrder', mode: 'supplement' }
    )
    assert.deepEqual(resolveBoutiqueSubmitAction({ selectPayType: 0 }), {
      method: 'createWithPay',
      mode: 'defeat'
    })
  })

  it('submits the same payload object and accepts only numeric or string zero', async () => {
    const payload = { orderCode: 'O-1' }
    let received
    const success = await submitBoutiqueOrder(
      { method: 'createWithPay', payload },
      {
        createWithPay: async value => {
          received = value
          return { code: '0', data: { id: 1 } }
        }
      }
    )
    assert.equal(received, payload)
    assert.equal(success.status, 'success')

    const failed = await submitBoutiqueOrder(
      { method: 'createWithPay', payload },
      { createWithPay: async () => ({ code: 1, message: '失败' }) }
    )
    assert.equal(failed.status, 'business-error')
    await assert.rejects(
      submitBoutiqueOrder({ method: 'missing', payload }, {}),
      /未配置精品提交接口/
    )
  })

  it('describes existing success navigation without invoking wx', () => {
    assert.deepEqual(
      buildSubmitUiResult({
        mode: 'prerecorded',
        response: { code: 0, data: {} },
        pageContext: {}
      }),
      {
        patch: {},
        message: '保存成功',
        navigation: { type: 'go', alias: 'pages.tabDateIndex' },
        refreshFlags: ['pageData']
      }
    )
    assert.deepEqual(
      buildSubmitUiResult({
        mode: 'correction',
        response: { code: 0, data: { orderCode: 'O-1' } },
        pageContext: {}
      }).navigation,
      {
        type: 'redirectTo',
        alias: 'confirmOrder',
        params: { orderCode: 'O-1', isErrorOrder: true }
      }
    )
  })

  it('allows only one concurrent task and releases the lock after success', async () => {
    let locked = false
    let calls = 0
    let resolveRequest
    const request = new Promise(resolve => { resolveRequest = resolve })
    const lock = {
      isLocked: () => locked,
      setLocked: value => { locked = value }
    }
    const first = runWithSubmitLock(lock, async () => {
      calls += 1
      await request
      return 'done'
    })
    const second = await runWithSubmitLock(lock, async () => {
      calls += 1
    })
    assert.deepEqual(second, { status: 'duplicate' })
    assert.equal(calls, 1)
    resolveRequest()
    assert.deepEqual(await first, { status: 'completed', value: 'done' })
    assert.equal(locked, false)
  })

  it('releases the lock after validation, payload or API errors', async () => {
    for (const error of [new Error('validation'), new Error('payload'), new Error('api')]) {
      let locked = false
      await assert.rejects(
        runWithSubmitLock(
          {
            isLocked: () => locked,
            setLocked: value => { locked = value }
          },
          async () => { throw error }
        ),
        new RegExp(error.message)
      )
      assert.equal(locked, false)
    }
  })
})