Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(expect): support expect.extend() api #4412

Merged
merged 11 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions expect/_equal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,7 @@ function constructorsEqual(a: object, b: object) {
* Deep equality comparison used in assertions
* @param c actual value
* @param d expected value
* @param strictCheck check value in strictMode
*
* @example
* ```ts
* import { equal } from "https://deno.land/std@$STD_VERSION/assert/equal.ts";
*
* equal({ foo: "bar" }, { foo: "bar" }); // Returns `true`
* equal({ foo: "bar" }, { foo: "baz" }); // Returns `false
* ```
* @param options for the equality check
*/
export function equal(c: unknown, d: unknown, options?: EqualOptions): boolean {
const { customTesters = [], strictCheck } = options || {};
Expand All @@ -36,7 +28,10 @@ export function equal(c: unknown, d: unknown, options?: EqualOptions): boolean {
return (function compare(a: unknown, b: unknown): boolean {
if (customTesters?.length) {
for (const customTester of customTesters) {
const pass = customTester.call(undefined, a, b, customTesters);
const testContext = {
equal,
};
const pass = customTester.call(testContext, a, b, customTesters);
if (pass !== undefined) {
return pass;
}
Expand Down
16 changes: 16 additions & 0 deletions expect/_extend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

import { Matchers } from "./_types.ts";

let extendMatchers = {};

export function getExtendMatchers() {
return extendMatchers;
}

export function setExtendMatchers(newExtendMatchers: Matchers) {
extendMatchers = {
...extendMatchers,
...newExtendMatchers,
};
}
119 changes: 119 additions & 0 deletions expect/_extend_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

import { expect } from "./expect.ts";
import { MatcherContext, Tester } from "./_types.ts";

type DbConnection = number;

declare module "./_types.ts" {
interface Expected {
toEqualBook: (expected: unknown) => ExtendMatchResult;
}
}

const CONNECTION_PROP = "__connection";
let DbConnectionId = 0;

class Author {
public name: string;
public [CONNECTION_PROP]: DbConnection;

constructor(name: string) {
this.name = name;
this[CONNECTION_PROP] = DbConnectionId++;
}
}

class Book {
public name: string;
public authors: Array<Author>;
public [CONNECTION_PROP]: DbConnection;

constructor(name: string, authors: Array<Author>) {
this.name = name;
this.authors = authors;
this[CONNECTION_PROP] = DbConnectionId++;
}
}

const areAuthorsEqual: Tester = (a: unknown, b: unknown) => {
const isAAuthor = a instanceof Author;
const isBAuthor = b instanceof Author;

if (isAAuthor && isBAuthor) {
return a.name === b.name;
} else if (isAAuthor === isBAuthor) {
return undefined;
} else {
return false;
}
};

const areBooksEqual: Tester = function (
this: MatcherContext,
a: unknown,
b: unknown,
customTesters: Tester[],
) {
const isABook = a instanceof Book;
const isBBook = b instanceof Book;

if (isABook && isBBook) {
return (a.name === b.name &&
this.equal(a.authors, b.authors, { customTesters: customTesters }));
} else if (isABook === isBBook) {
return undefined;
} else {
return false;
}
};

const book1 = new Book("Book 1", [
new Author("Author 1"),
new Author("Author 2"),
]);
const book1b = new Book("Book 1", [
new Author("Author 1"),
new Author("Author 2"),
]);

expect.addEqualityTesters([
areAuthorsEqual,
areBooksEqual,
]);

expect.extend({
toEqualBook(context, expected) {
const actual = context.value as Book;
const result = context.equal(expected, actual, {
customTesters: context.customTesters,
});

return {
message: () =>
`Expected Book object: ${expected.name}. Actual Book object: ${actual.name}`,
pass: result,
};
},
toBeWithinRange(context, floor: number, ceiling: number) {
const actual = context.value as number;
const pass = actual >= floor && actual <= ceiling;
if (pass) {
return {
message: () =>
`expected ${actual} not to be within range ${floor} - ${ceiling}`,
pass: true,
};
} else {
return {
message: () =>
`expected ${actual} to be within range ${floor} - ${ceiling}`,
pass: false,
};
}
},
});

Deno.test("expect.extend() api test case", () => {
expect(book1).toEqualBook(book1b);
});
10 changes: 9 additions & 1 deletion expect/_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,24 @@
export interface MatcherContext {
value: unknown;
isNot: boolean;
equal: (a: unknown, b: unknown, options?: EqualOptions) => boolean;
customTesters: Tester[];
customMessage: string | undefined;
}

export type Matcher = (
context: MatcherContext,
...args: any[]
) => MatchResult;
) => MatchResult | ExtendMatchResult;

export type Matchers = {
[key: string]: Matcher;
};
export type MatchResult = void | Promise<void> | boolean;
export type ExtendMatchResult = {
message: () => string;
pass: boolean;
};
export type AnyConstructor = new (...args: any[]) => any;

export type Tester = (
Expand Down Expand Up @@ -88,6 +93,9 @@ export interface Expected {
not: Expected;
resolves: Async<Expected>;
rejects: Async<Expected>;
// This declaration prepares for the `expect.extend` and just only let
// compiler pass, the more concrete type definition is defined by user
[name: string]: unknown;
}

export type MatcherKey = keyof Omit<Expected, "not" | "resolves" | "rejects">;
Expand Down
30 changes: 26 additions & 4 deletions expect/expect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,19 @@

import type {
Expected,
ExtendMatchResult,
Matcher,
MatcherContext,
MatcherKey,
Matchers,
} from "./_types.ts";
import { AssertionError } from "../assert/assertion_error.ts";
import {
addCustomEqualityTesters,
getCustomEqualityTesters,
} from "./_custom_equality_tester.ts";
import { equal } from "./_equal.ts";
import { getExtendMatchers, setExtendMatchers } from "./_extend.ts";
import {
toBe,
toBeCloseTo,
Expand Down Expand Up @@ -94,7 +98,7 @@
toThrow,
};

export function expect(value: unknown, customMessage?: string): Expected {
export const expect = (value: unknown, customMessage?: string): Expected => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, thank you. I missed it.

let isNot = false;
let isPromised = false;
const self: Expected = new Proxy<Expected>(
Expand Down Expand Up @@ -132,7 +136,12 @@
return self;
}

const matcher: Matcher = matchers[name as MatcherKey];
const extendMatchers: Matchers = getExtendMatchers();
const allMatchers = {
...extendMatchers,
...matchers,
};
const matcher: Matcher = allMatchers[name as MatcherKey];
if (!matcher) {
throw new TypeError(
typeof name === "string"
Expand All @@ -145,14 +154,26 @@
function applyMatcher(value: unknown, args: unknown[]) {
const context: MatcherContext = {
value,
equal,
isNot: false,
customMessage,
customTesters: getCustomEqualityTesters(),
};
if (isNot) {
context.isNot = true;
}
matcher(context, ...args);
if (name in extendMatchers) {
const result = matcher(context, ...args) as ExtendMatchResult;
if (context.isNot) {
if (result.pass) {
throw new AssertionError(result.message());
}

Check warning on line 170 in expect/expect.ts

View check run for this annotation

Codecov / codecov/patch

expect/expect.ts#L168-L170

Added lines #L168 - L170 were not covered by tests
} else if (!result.pass) {
throw new AssertionError(result.message());
}

Check warning on line 173 in expect/expect.ts

View check run for this annotation

Codecov / codecov/patch

expect/expect.ts#L172-L173

Added lines #L172 - L173 were not covered by tests
} else {
matcher(context, ...args);
}
}

return isPromised
Expand All @@ -166,9 +187,10 @@
);

return self;
}
};

expect.addEqualityTesters = addCustomEqualityTesters;
expect.extend = setExtendMatchers;
expect.anything = anything;
expect.any = any;
expect.arrayContaining = arrayContaining;