Skip to content

Instantly share code, notes, and snippets.

@loucadufault
Last active January 30, 2022 20:51
Show Gist options
  • Select an option

  • Save loucadufault/86fb2de0fc2d195edaf738fb66f10aac to your computer and use it in GitHub Desktop.

Select an option

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
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"]);
});
// 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