assert.js
This file
Path
test/helpers/assert.js
70 lines · 2.5 KiB · JavaScript
Last changed by
TweaksSindre Sorhusbefore adoption698a1b8
History of this fileTake it
TweaksSindre Sorhusbefore adoption698a1b8
lines 1–70why, one step back1import assert from 'node:assert/strict';2import isPlainObject from 'is-plain-obj';34/*5`t.throws()` and `t.throwsAsync()` returned the thrown error, which most tests assert on.6`assert.throws()` and `assert.rejects()` do not, so the error is captured with their validation function instead.7*/89const checkExpectation = (error, expectation) => {10 if (expectation === undefined) {11 return;12 }1314 // A constructor or a RegExp has no own properties to compare, so it would always pass15 if (!isPlainObject(expectation)) {16 throw new TypeError('The expectation must be a plain object like `{message}` or `{instanceOf}`.');17 }1819 // `assert.throws()` compares every own property of the expectation against the error, but it does not20 // know about `instanceOf`, which AVA validated. It is therefore checked separately.21 const {instanceOf, ...properties} = expectation;22 if (instanceOf !== undefined) {23 assert.ok(error instanceof instanceOf, `The error is not an instance of ${instanceOf.name}`);24 }2526 if (Object.keys(properties).length > 0) {27 // Rethrowing checks the expectation with the same `message`, `code` and constructor logic.28 assert.throws(() => {29 throw error;30 }, properties);31 }32};3334export const assertThrows = (synchronousFunction, expectation) => {35 let error;36 assert.throws(synchronousFunction, thrownError => {37 error = thrownError;38 return true;39 });4041 checkExpectation(error, expectation);42 return error;43};4445export const assertRejects = async (promise, expectation) => {46 let error;47 await assert.rejects(promise, thrownError => {48 error = thrownError;49 return true;50 });5152 checkExpectation(error, expectation);53 return error;54};5556/*57Like `t.like()`, this compares a subset of the properties of an object, whatever its prototype. Nested plain objects are compared the same way, unless they are empty. Any other value must be deeply equal, including arrays, which is stricter than `t.like()`.58`assert.partialDeepStrictEqual()` is not used: it requires the prototype to be the same, which never holds when the value is an error, and an empty array matches any array.59The properties are read directly, so non-enumerable ones like `error.cause` are included.60*/61export const assertLike = (value, expectedSubset, path = 'value') => {62 for (const [key, expectedValue] of Object.entries(expectedSubset)) {63 const keyPath = `${path}.${key}`;64 if (isPlainObject(expectedValue) && Object.keys(expectedValue).length > 0) {65 assertLike(value[key], expectedValue, keyPath);66 } else {67 assert.deepEqual(value[key], expectedValue, `${keyPath} is not like the expected value`);68 }69 }70};