diff --git a/README.md b/README.md index 40f6870..6bb778e 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_900 TILs and counting..._ +_901 TILs and counting..._ --- @@ -339,6 +339,7 @@ _900 TILs and counting..._ - [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md) - [Spread The Rest With ES6](javascript/spread-the-rest-with-es6.md) - [String Interpolation With Template Literals](javascript/string-interpolation-with-template-literals.md) +- [Support Nested Matching In Custom Jest Matchers](javascript/support-nested-matching-in-custom-jest-matchers.md) - [Test Coverage Stats With Jest](javascript/test-coverage-stats-with-jest.md) - [The Comma Operator](javascript/the-comma-operator.md) - [Throttling A Function Call](javascript/throttling-a-function-call.md) diff --git a/javascript/support-nested-matching-in-custom-jest-matchers.md b/javascript/support-nested-matching-in-custom-jest-matchers.md new file mode 100644 index 0000000..35a32a9 --- /dev/null +++ b/javascript/support-nested-matching-in-custom-jest-matchers.md @@ -0,0 +1,48 @@ +# Support Nested Matching In Custom Jest Matchers + +A [custom Jest matcher](define-a-custom-jest-matcher) can use standard +JavaScript operations to evaluate if the given value(s) should pass or not. + +```javascript +expect.extend({ + toContainValue(receivedArray, containedValue) { + const pass = + receivedArray.some(value => value === containedValue); + + // return formatted pass/not-pass objects with messages + return { ... } + } +}); +``` + +This approach alone doesn't support the power of Jest's nested matchers. +Consider trying to use this like so: + +```javascript +expect(['a', 2, true]).toContainValue(expect.any(Number)); +``` + +This would fail, even though there is a value in there that matches +`any(Number)`. + +Jest ships with some [Jasmine](https://jasmine.github.io/) utilities that you +can use, just as Jest does internally, to perform nested matching: + +```javascript +const { equals } = require("expect/build/jasmineUtils"); + +expect.extend({ + toContainValue(receivedArray, containedValue) { + const pass = + receivedArray.some(value => equals(value, containedValue)); + + // return formatted pass/not-pass objects with messages + return { ... } + } +}); +``` + +That `equals` utility knows how to compare raw values like integers, booleans, +and even whole objects against nested `expect` matchers. + +[source](https://github.com/facebook/jest/issues/8295#issuecomment-482545274)