Skip to content

Commit

Permalink
Merge pull request #137 from drashland/fix/nested-calls-not-tracked
Browse files Browse the repository at this point in the history
fix: nested calls in mock not being tracked
  • Loading branch information
crookse authored Feb 22, 2022
2 parents e469835 + 309b6e8 commit 6711cca
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
13 changes: 11 additions & 2 deletions src/mock_builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,19 @@ export class MockBuilder<T> {
mock.calls[method] = 0;
}
mock[method] = function (...args: unknown[]) {
// Add tracking
mock.calls[method]++;
return (original[method as keyof T] as unknown as (

// Make sure the method calls its original self
let unbound = (original[method as keyof T] as unknown as (
...params: unknown[]
) => unknown)(...args);
) => unknown);

// When method calls its original self, let `this` be the mock. Reason
// being the mock has tracking and the original does not.
const bound = unbound.bind(mock);

return bound(...args);
};
} else {
// copy nativeMethod directly without mocking
Expand Down
36 changes: 33 additions & 3 deletions tests/integration/mock_test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
import { Rhum } from "../../mod.ts";

class MathService {
public add(num1: number, num2: number): number {
public add(
num1: number,
num2: number,
useNestedAdd: boolean = false,
): number {
if (useNestedAdd) {
return this.nestedAdd(num1, num2);
}
return num1 + num2;
}

public nestedAdd(num1: number, num2: number): number {
return num1 + num2;
}
}
Expand All @@ -14,8 +25,12 @@ class TestObject {
this.math_service = mathService;
this.name = name;
}
public sum(num1: number, num2: number): number {
const sum = this.math_service.add(num1, num2);
public sum(
num1: number,
num2: number,
useNestedAdd: boolean = false,
): number {
const sum = this.math_service.add(num1, num2, useNestedAdd);
return sum;
}
protected protectedMethod() {
Expand Down Expand Up @@ -93,6 +108,21 @@ Rhum.testPlan("mock_test.ts", () => {
Rhum.asserts.assertEquals(mockMathService.calls.add, 1);
});

Rhum.testCase("call count for outside nested function is increased", () => {
const mockMathService = Rhum
.mock(MathService)
.create();
const mockTestObject = Rhum
.mock(TestObject)
.withConstructorArgs("has mocked math service", mockMathService)
.create();
Rhum.asserts.assertEquals(mockMathService.calls.add, 0);
Rhum.asserts.assertEquals(mockMathService.calls.nestedAdd, 0);
mockTestObject.sum(1, 1, true);
Rhum.asserts.assertEquals(mockMathService.calls.add, 1);
Rhum.asserts.assertEquals(mockMathService.calls.nestedAdd, 1);
});

Rhum.testCase("Native Request mock", async () => {
const router = Rhum.mock(TestRequestHandler).create();

Expand Down

0 comments on commit 6711cca

Please sign in to comment.