Enums
.toBeEnum(enum)
Also available as an asymmetric matcher, expect.ofEnum(enum)
.
Use .toBeEnum
to assert that a value is a member of an enum (or const object).
enum Direction { Up, Down, Left, Right, } it("is a member of the numeric enum", () => { expect(Direction.Up).toBeEnum(Direction); });
Tests
Aliasing
expect.ofEnum
to expect.enum
As enum
is a reserved word in Javascript, it is not possible to export a matcher with this name. However, you can alias it in your setup file:
- Jest
- Jest (no globals)
- Vitest
test-setup.ts
import { exactly, ofEnum } from "mix-n-matchers";
import type { MixNMatchersFrom, AsymmetricMixNMatchersFrom } from "mix-n-matchers";
const matchers = {
exactly,
enum: ofEnum,
};
expect.extend(matchers);
declare global {
namespace jest {
interface Matchers<R, T> extends MixNMatchersFrom<typeof matchers, R, T> {}
interface Expect extends AsymmetricMixNMatchersFrom<typeof matchers> {
enum: AsymmetricMatchers["ofEnum"];
}
interface InverseAsymmetricMatchers
extends AsymmetricMixNMatchersFrom<typeof matchers> {
enum: AsymmetricMatchers["ofEnum"];
}
}
}
test-setup.ts
import { expect } from "@jest/globals";
import { exactly, ofEnum } from "mix-n-matchers";
import type { MixNMatchersFrom, AsymmetricMixNMatchersFrom } from "mix-n-matchers";
const matchers = {
exactly,
enum: ofEnum,
};
expect.extend(matchers);
declare module "@jest/expect" {
interface Matchers<R, T> extends MixNMatchersFrom<typeof matchers, R, T> {}
interface AsymmetricMatchers
extends AsymmetricMixNMatchersFrom<typeof matchers> {
enum: AsymmetricMatchers["ofEnum"];
}
}
test-setup.ts
import { expect } from "vitest";
import { exactly, ofEnum } from "mix-n-matchers";
import type { MixNMatchersFrom, AsymmetricMixNMatchersFrom } from "mix-n-matchers";
const matchers = {
exactly,
enum: ofEnum,
};
expect.extend(matchers);
declare module "vitest" {
interface Assertion<T> extends MixNMatchersFrom<typeof matchers, void, T> {}
interface AsymmetricMatchersContaining
extends AsymmetricMixNMatchersFrom<typeof matchers> {
enum: AsymmetricMatchers["ofEnum"];
}
}
After this setup, you should be able to use expect.enum
as a matcher.
expect(mock).toBeCalledWith(expect.enum(MyEnum));
This is automatically done for you with the auto-setup files.