Skip to content

Commit

Permalink
add castArray tests
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 13, 2024
1 parent 637a1e1 commit 23f62a1
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
33 changes: 33 additions & 0 deletions tests/casted/castArray.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as _ from 'radashi'

describe('castArray', () => {
test('mutable arrays', () => {
const input: number[] = [1, 2, 3]
expectTypeOf(_.castArray(input)).toEqualTypeOf<number[]>()
})
test('readonly arrays', () => {
const input: readonly number[] = [1, 2, 3]

// castArray clones the input array, so "readonly" is removed.
expectTypeOf(_.castArray(input)).toEqualTypeOf<number[]>()
})
test('union type with array type and primitive type', () => {
const input = 1 as number[] | number
const output = _.castArray(input)

expectTypeOf(output).toEqualTypeOf<number[] | [number]>()
})
test('union type with two array types', () => {
const input = [1, 2, 3] as number[] | readonly string[]
const output = _.castArray(input)

expectTypeOf(output).toEqualTypeOf<number[] | string[]>()
})
test('primitive types', () => {
expectTypeOf(_.castArray(1)).toEqualTypeOf<[number]>()
expectTypeOf(_.castArray('a')).toEqualTypeOf<[string]>()
expectTypeOf(_.castArray(true)).toEqualTypeOf<[true] | [false]>()
expectTypeOf(_.castArray(null)).toEqualTypeOf<[null]>()
expectTypeOf(_.castArray(undefined)).toEqualTypeOf<[undefined]>()
})
})
31 changes: 31 additions & 0 deletions tests/casted/castArray.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as _ from 'radashi'

describe('castArray', () => {
test('return the same array if input is an array', () => {
const input = [1, 2, 3]
expect(_.castArray(input)).toEqual(input)
})
test('return a new array with the same elements if input is an array', () => {
const input = [1, 2, 3]
const result = _.castArray(input)
expect(result).toEqual(input)
expect(result).not.toBe(input) // Ensure it's a copy
})
test('return an array with the input if input is not an array', () => {
const input = 1
expect(_.castArray(input)).toEqual([input])
})
test('handle primitives', () => {
expect(_.castArray(1)).toEqual([1])
expect(_.castArray('a')).toEqual(['a'])
expect(_.castArray(true)).toEqual([true])
expect(_.castArray(null)).toEqual([null])
expect(_.castArray(undefined)).toEqual([undefined])
})
test('handle objects and functions', () => {
const obj = { a: 1 }
const func = () => {}
expect(_.castArray(obj)).toEqual([obj])
expect(_.castArray(func)).toEqual([func])
})
})

0 comments on commit 23f62a1

Please sign in to comment.