|
| 1 | +/* |
| 2 | + * @adonisjs/core |
| 3 | + * |
| 4 | + * (c) AdonisJS |
| 5 | + * |
| 6 | + * For the full copyright and license information, please view the LICENSE |
| 7 | + * file that was distributed with this source code. |
| 8 | + */ |
| 9 | + |
| 10 | +import { test } from '@japa/runner' |
| 11 | +import { safeTiming } from '../src/helpers/safe_timing.ts' |
| 12 | + |
| 13 | +test.group('safeTiming', () => { |
| 14 | + test('enforces minimum execution time', async ({ assert }) => { |
| 15 | + const start = performance.now() |
| 16 | + |
| 17 | + await safeTiming(200, async () => { |
| 18 | + return 'done' |
| 19 | + }) |
| 20 | + |
| 21 | + const elapsed = performance.now() - start |
| 22 | + assert.isAbove(elapsed, 190) |
| 23 | + }) |
| 24 | + |
| 25 | + test('returns the callback result', async ({ assert }) => { |
| 26 | + const result = await safeTiming(50, async () => { |
| 27 | + return { message: 'hello' } |
| 28 | + }) |
| 29 | + |
| 30 | + assert.deepEqual(result, { message: 'hello' }) |
| 31 | + }) |
| 32 | + |
| 33 | + test('does not add delay when callback already exceeds minimum time', async ({ assert }) => { |
| 34 | + const start = performance.now() |
| 35 | + |
| 36 | + await safeTiming(50, async () => { |
| 37 | + await new Promise((resolve) => setTimeout(resolve, 100)) |
| 38 | + return 'slow' |
| 39 | + }) |
| 40 | + |
| 41 | + const elapsed = performance.now() - start |
| 42 | + assert.isAbove(elapsed, 95) |
| 43 | + assert.isBelow(elapsed, 200) |
| 44 | + }) |
| 45 | + |
| 46 | + test('returnEarly skips the minimum time wait', async ({ assert }) => { |
| 47 | + const start = performance.now() |
| 48 | + |
| 49 | + await safeTiming(500, async (box) => { |
| 50 | + box.returnEarly() |
| 51 | + return 'fast' |
| 52 | + }) |
| 53 | + |
| 54 | + const elapsed = performance.now() - start |
| 55 | + assert.isBelow(elapsed, 100) |
| 56 | + }) |
| 57 | + |
| 58 | + test('still waits minimum time when callback throws', async ({ assert }) => { |
| 59 | + const start = performance.now() |
| 60 | + |
| 61 | + await assert.rejects(async () => { |
| 62 | + await safeTiming(200, async () => { |
| 63 | + throw new Error('kaboom') |
| 64 | + }) |
| 65 | + }, 'kaboom') |
| 66 | + |
| 67 | + const elapsed = performance.now() - start |
| 68 | + assert.isAbove(elapsed, 190) |
| 69 | + }) |
| 70 | + |
| 71 | + test('skips wait on error when returnEarly was called', async ({ assert }) => { |
| 72 | + const start = performance.now() |
| 73 | + |
| 74 | + await assert.rejects(async () => { |
| 75 | + await safeTiming(500, async (box) => { |
| 76 | + box.returnEarly() |
| 77 | + throw new Error('early error') |
| 78 | + }) |
| 79 | + }, 'early error') |
| 80 | + |
| 81 | + const elapsed = performance.now() - start |
| 82 | + assert.isBelow(elapsed, 100) |
| 83 | + }) |
| 84 | +}) |
0 commit comments