Skip to content

Commit

Permalink
Throw error when array does not have the same size (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
abdala authored Feb 3, 2025
1 parent a91c425 commit 34de111
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
11 changes: 10 additions & 1 deletion assert/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ interface ExtraAssertions {
): asserts actual is Partial<T>
}

const formatValues = <A, E>(actual: A, expected: E) => `\n\nActual:
${JSON.stringify(actual, undefined, 2)}\n
Expected:
${JSON.stringify(expected, undefined, 2)}\n`

const assertions: ExtraAssertions = {
objectContains<T extends Record<string, any>>(
actual: Record<string, any>,
Expand All @@ -19,7 +24,11 @@ const assertions: ExtraAssertions = {
debug('[ASSERT] objectContains', actual, expected)

if (typeof actual !== 'object' || typeof expected !== 'object') {
throw new Error('Both actual and expected values must be objects');
throw new Error(`Both actual and expected values must be objects. ${formatValues(actual, expected)}`);
}

if (Array.isArray(actual) && Array.isArray(expected) && actual.length !== expected.length) {
throw new Error(`Both actual and expected should have the same number of elements. ${formatValues(actual, expected)}`);
}

const expectedKeys = Object.keys(expected);
Expand Down
19 changes: 19 additions & 0 deletions assert/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,29 @@ test('It partially check object properties', () => {
test('It fails when object properties does not match', () => {
const actual = {a: 'b', c: 'd'}
const expected = {c: 'e'}
let asserted = 0

try {
extraAssert.objectContains(actual, expected)
} catch (error) {
nodeAssert.equal(error.code, 'ERR_ASSERTION')
asserted = 1
}

nodeAssert.ok(asserted)
})

test('It fails when array does not have the same size', () => {
const actual = [{a: 'b'}, {c: 'd'}]
const expected = [{c: 'e'}]
let asserted = 0

try {
extraAssert.objectContains(actual, expected)
} catch (error) {
nodeAssert.ok(error.message.indexOf('Both actual and expected should have the same number of elements') !== -1)
asserted = 1
}

nodeAssert.ok(asserted)
})

0 comments on commit 34de111

Please sign in to comment.