Last active
January 30, 2022 20:51
-
-
Save loucadufault/86fb2de0fc2d195edaf738fb66f10aac to your computer and use it in GitHub Desktop.
Jest expect matcher extension for asserting whether the received object has only the properties specified via a list to the matcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| test('received response only exposes the public fields', () => { | |
| const res = await request | |
| .post('/items') | |
| .send(newItem) | |
| .expect(status.CREATED); | |
| expect(res.body).toOnlyHaveProperties(["id", "name", "color"]); | |
| }); | |
| test('returned object is extended', () => { | |
| const ret = addAnotherProp({a: 1, b: 2}); | |
| expect(ret).not.toOnlyHaveProperties(["a", "b"]); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // see https://jestjs.io/docs/expect#expectextendmatchers | |
| expect.extend({ | |
| function toOnlyHaveProperties(received, allowedProps) { | |
| const receivedProps = Object.keys(received); | |
| const pass = JSON.stringify(receivedProps.sort()) === JSON.stringify(allowedProps.sort()); | |
| if (pass) { | |
| return { | |
| message: () => | |
| `expected ${received} to not only have properties ${JSON.stringify(allowedProps)}`, | |
| pass: true, | |
| }; | |
| } else { | |
| return { | |
| message: () => | |
| `expected ${received} to only have properties ${JSON.stringify(allowedProps)}`, | |
| pass: false, | |
| }; | |
| } | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment