Skip to content

Commit

Permalink
Add recursive matching within objectContaining()
Browse files Browse the repository at this point in the history
  • Loading branch information
Johan Blumenberg committed Mar 28, 2023
1 parent f25ce84 commit 0dc7ecc
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/matcher/type/ObjectContainingMatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@ export class ObjectContainingMatcher extends Matcher {
}

public match(value: Object): boolean {
return _.isMatch(value, this.expectedValue);
return _.isMatchWith(value, this.expectedValue, (objValue, srcValue) => {
if (srcValue instanceof Matcher) {
return srcValue.match(objValue);
} else {
return undefined;
}
});
}

public toString(): string {
Expand Down
30 changes: 29 additions & 1 deletion test/matcher/type/ObjectContainingMatcher.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Matcher} from "../../../src/matcher/type/Matcher";
import {objectContaining} from "../../../src/ts-mockito";
import {objectContaining, startsWith} from "../../../src/ts-mockito";

describe("ObjectContainingMatcher", () => {
describe("checking if source object contains given object", () => {
Expand Down Expand Up @@ -34,6 +34,34 @@ describe("ObjectContainingMatcher", () => {
});
});

describe("accept matchers as values", () => {
it("should match using matcher as value", () => {
const testObj: Matcher = objectContaining({ key: startsWith("abc") }) as unknown as Matcher;
const result = testObj.match({key: "abcdef"});
expect(result).toBeTruthy();
});

it("should not match using matcher as value with mismatching value", () => {
const testObj: Matcher = objectContaining({ key: startsWith("abc") }) as unknown as Matcher;
const result = testObj.match({key: "def"});
expect(result).toBeFalsy();
});
});

describe("accept matchers as values in arrays", () => {
it("should match using matcher as value", () => {
const testObj: Matcher = objectContaining({ key: [startsWith("abc")] }) as unknown as Matcher;
const result = testObj.match({key: ["abcdef"]});
expect(result).toBeTruthy();
});

it("should not match using matcher as value with mismatching value", () => {
const testObj: Matcher = objectContaining({ key: [startsWith("abc")] }) as unknown as Matcher;
const result = testObj.match({key: ["def"]});
expect(result).toBeFalsy();
});
});

describe("types", () => {
it("deduce type from return value", () => {
const result: { a: boolean, b: boolean } = objectContaining({a: true});
Expand Down

0 comments on commit 0dc7ecc

Please sign in to comment.