From 5c29ea77aed2fbf1c1b337133fbcf23009ff9533 Mon Sep 17 00:00:00 2001 From: Benjamin Lupton Date: Wed, 29 Nov 2023 15:16:38 +0800 Subject: [PATCH] add notContains, output comparison in contains, use .includes --- HISTORY.md | 4 ++++ source/index.ts | 27 ++++++++++++++++++++++++++- source/test.ts | 7 +++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/HISTORY.md b/HISTORY.md index c0d1d63..85f4f4d 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,9 @@ # History +- Added `notContains` +- `contains` and `notContains` now output the failed comparison, rather than just the failure +- No need to not use `String.prototype.includes` as it is supported by all environments we support + ## v11.6.0 2023 November 24 - Updated dependencies, [base files](https://github.com/bevry/base), and [editions](https://editions.bevry.me) using [boundation](https://github.com/bevry/boundation) diff --git a/source/index.ts b/source/index.ts index e7bdd39..679bba3 100644 --- a/source/index.ts +++ b/source/index.ts @@ -2,11 +2,13 @@ // Polyfill for older node versions if (Array.prototype.includes == null) { + // Array.prototype.includes missing on Node.js v4, first added in Node.js v6 // eslint-disable-next-line no-extend-native Array.prototype.includes = function (searchElement) { return this.indexOf(searchElement) !== -1 } } +// String.prototype.includes included on Node.js v4 // Import import { @@ -322,8 +324,9 @@ export function contains( if (testName == null) testName = `Expected [${actual}] to contain [${expected}]` try { - _ok(actual.indexOf(expected) !== -1, testName) + _ok(actual.includes(expected) === true, testName) } catch (checkError: any) { + logComparison(actual, expected, checkError) if (next) { next(checkError) return @@ -334,6 +337,28 @@ export function contains( if (next) next() } +/** Checks to see if the actual result does not contain the expected result .*/ +export function notContains( + actual: any, + expected: any, + testName = 'does not contain assertion', + next?: Errback +): void | never { + if (testName == null) + testName = `Expected [${actual}] to not contain [${expected}]` + try { + _ok(actual.includes(expected) === false, testName) + } catch (checkError: any) { + logComparison(actual, expected, checkError) + if (next) { + next(checkError) + return + } else { + throw checkError + } + } + if (next) next() +} /** Checks to see if an error was as expected, if a failure occurs it will output detailed information */ export function errorEqual( actualError: any, diff --git a/source/test.ts b/source/test.ts index d283a7c..a8b6b22 100644 --- a/source/test.ts +++ b/source/test.ts @@ -94,6 +94,13 @@ kava.suite('assert-helpers', function (suite, test) { fail() } catch (err) {} }) + test('notContains', function () { + helpers.notContains('ab', 'c') + try { + helpers.notContains('ab', 'a') + fail() + } catch (err) {} + }) test('errorEqual', function () { const a = new Error('abc') helpers.errorEqual(a, 'abc')