Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created February 4, 2022 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/ff9758bca84d1470386588866c18c133 to your computer and use it in GitHub Desktop.
Save tmcw/ff9758bca84d1470386588866c18c133 to your computer and use it in GitHub Desktop.
import type { Either } from "purify-ts";
import { matcherHint } from "jest-matcher-utils";
import { diff } from "jest-diff";
const passMessage = (expect: "Left" | "Right") => () =>
matcherHint(`.not.to${expect}`, "received", "") +
"\n\n" +
`Expected Either to be ${expect}`;
const failMessage = (expect: "Left" | "Right") => () =>
matcherHint(`.toBe${expect}`, "received", "") +
"\n\n" +
`Expected Either to be ${expect}`;
const failRight = (value: string) => () =>
matcherHint(".toEqualRight", "received", "") +
"\n\n" +
"Expected Either to be Right, received Left." +
"\n\n" +
value;
expect.extend({
toBeRight(received: Either<unknown, unknown>) {
const pass = received.isRight();
return {
pass: pass,
message: pass ? passMessage("Right") : failMessage("Right"),
};
},
toBeLeft(received: Either<unknown, unknown>) {
const pass = received.isLeft();
return {
pass: pass,
message: pass ? passMessage("Left") : failMessage("Left"),
};
},
toEqualRight(received: Either<unknown, unknown>, expected: unknown) {
const { equals, utils, expand } = this;
const options = {
comment: "Right value equality",
isNot: this.isNot,
promise: this.promise,
};
return received.caseOf({
Left(value) {
return {
pass: false,
message: failRight(utils.printReceived(value)),
};
},
Right(value) {
if (equals(value, expected)) {
return {
pass: true,
message: passMessage("Right"),
};
} else {
return {
pass: false,
message: () => {
const diffString = diff(expected, received, {
expand,
});
return (
utils.matcherHint(
"toEqualRight",
undefined,
undefined,
options
) +
"\n\n" +
(diffString && diffString.includes("- Expect")
? `Difference:\n\n${diffString}`
: `Expected: ${utils.printExpected(expected)}\n` +
`Received: ${utils.printReceived(received)}`)
);
},
};
}
},
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment