You need to sign in or sign up before continuing.
dailyReportNewVersionGate.test.mjs 2.63 KB
import { describe, it, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'

describe('dailyReportNewVersionGate', async () => {
	const {
		resolveShopMerchantId,
		parseIsNeedResponse,
		fetchDailyReportNewVersionMenuVisible,
		__setApiClientForTest,
		clearDailyReportNewVersionCache
	} = await import('../../utils/dailyReportNewVersionGate.js')

	let apiCalls

	beforeEach(() => {
		apiCalls = []
		clearDailyReportNewVersionCache()
		__setApiClientForTest({
			dailyReportNewVersionIsNeed(data) {
				apiCalls.push(data)
				return Promise.resolve({ code: 0, data: true })
			}
		})
	})

	afterEach(() => {
		__setApiClientForTest(null)
		clearDailyReportNewVersionCache()
	})

	it('resolveShopMerchantId returns string id or empty', () => {
		assert.equal(resolveShopMerchantId({ shopMerchantId: 123 }), '123')
		assert.equal(resolveShopMerchantId({}), '')
		assert.equal(resolveShopMerchantId({ shopMerchantId: '' }), '')
	})

	it('resolveShopMerchantId falls back to default4SStoreInfo merchantId', () => {
		assert.equal(
			resolveShopMerchantId({
				default4SStoreInfo: { merchantId: 'store-1' }
			}),
			'store-1'
		)
		assert.equal(
			resolveShopMerchantId({
				default4SStoreInfo_crowdFunding: { merchantId: 'cf-1' }
			}),
			'cf-1'
		)
		assert.equal(
			resolveShopMerchantId({
				shopMerchantId: 'primary',
				default4SStoreInfo: { merchantId: 'secondary' }
			}),
			'primary'
		)
	})

	it('parseIsNeedResponse accepts boolean and loose string', () => {
		assert.equal(parseIsNeedResponse({ code: 0, data: true }), true)
		assert.equal(parseIsNeedResponse({ code: 0, data: 'true' }), true)
		assert.equal(parseIsNeedResponse({ code: 0, data: false }), false)
		assert.equal(parseIsNeedResponse({ code: 1, data: true }), false)
	})

	it('fetch returns false when merchantId empty without calling api', async () => {
		const visible = await fetchDailyReportNewVersionMenuVisible('')
		assert.equal(visible, false)
		assert.equal(apiCalls.length, 0)
	})

	it('fetch returns false on api error', async () => {
		__setApiClientForTest({
			dailyReportNewVersionIsNeed() {
				return Promise.reject(new Error('network'))
			}
		})
		const visible = await fetchDailyReportNewVersionMenuVisible('m1')
		assert.equal(visible, false)
	})

	it('fetch caches result within TTL', async () => {
		let callCount = 0
		__setApiClientForTest({
			dailyReportNewVersionIsNeed() {
				callCount += 1
				return Promise.resolve({ code: 0, data: true })
			}
		})
		assert.equal(await fetchDailyReportNewVersionMenuVisible('m-cache'), true)
		assert.equal(await fetchDailyReportNewVersionMenuVisible('m-cache'), true)
		assert.equal(callCount, 1)
	})
})