File tree Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Original file line number Diff line number Diff line change @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99
1010For a steady stream of TILs, [ sign up for my newsletter] ( https://tinyletter.com/jbranchaud ) .
1111
12- _ 898 TILs and counting..._
12+ _ 899 TILs and counting..._
1313
1414---
1515
@@ -300,6 +300,7 @@ _898 TILs and counting..._
300300- [ Create Bootstrapped Apps With Yarn] ( javascript/create-bootstrapped-apps-with-yarn.md )
301301- [ Custom Type Checking Error Messages With Yup] ( javascript/custom-type-checking-error-messages-with-yup.md )
302302- [ Default And Named Exports From The Same Module] ( javascript/default-and-named-exports-from-the-same-module.md )
303+ - [ Define A Custom Jest Matcher] ( javascript/define-a-custom-jest-matcher.md )
303304- [ Destructure With Access To Nested Value And Parent Value] ( javascript/destructure-with-access-to-nested-value-and-parent-value.md ) ;
304305- [ Destructuring The Rest Of An Array] ( javascript/destructuring-the-rest-of-an-array.md )
305306- [ Enable ES7 Transforms With react-rails] ( javascript/enable-es7-transforms-with-react-rails.md )
Original file line number Diff line number Diff line change 1+ # Define A Custom Jest Matcher
2+
3+ Though [ Jest's built-in
4+ matchers] ( https://jestjs.io/docs/en/expect ) will get you pretty
5+ far in most testing scenarios, you may find yourself in a testing situation
6+ better served by a custom matcher. Custom matchers can be defined using the
7+ [ ` expect.extend() `
8+ function] ( https://jestjs.io/docs/en/expect#expectextendmatchers ) .
9+
10+ Here is an example of a matcher that can check equality of two objects based
11+ solely on their ` id ` property.
12+
13+ ``` javascript
14+ expect .extend ({
15+ toHaveMatchingId (recieved , expected ) {
16+ const pass = recieved .id === expected .id ;
17+
18+ if (pass) {
19+ return {
20+ pass: true ,
21+ message: ` Actual ${ recieved .id } matches expected ${ expected .id } `
22+ };
23+ } else {
24+ return {
25+ pass: false ,
26+ message: ` Actual ${ recieved .id } does not match expected ${ expected .id } `
27+ };
28+ }
29+ }
30+ });
31+ ```
32+
33+ This defines the name of the matcher (` toHaveMatchingId ` ), contains some logic
34+ to figure out whether ` received ` and ` expected ` pass the matcher, and then two
35+ return conditions (` pass: true ` and ` pass: false ` ) with accompanying messages.
36+
37+ It can then be used like any other Jest matcher:
38+
39+ ``` javascript
40+ test (" compare objects" , () => {
41+ expect ({ id: " 001" }).toHaveMatchingId ({ id: " 001" });
42+ expect ({ id: " 001" }).toHaveMatchingId ({ id: " 002" });
43+ });
44+ ```
45+
46+ Check out a [ live example] ( https://codesandbox.io/s/focused-bush-vw2s5 ) .
You can’t perform that action at this time.
0 commit comments