Skip to content

Commit

Permalink
feat(mock): add onceReturnValue mock method
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Dec 13, 2021
1 parent 52f6336 commit 53c1e9f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
15 changes: 14 additions & 1 deletion mock/fn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,19 @@ function fn(
const onceImplementation = (
implementation: (...args: unknown[]) => unknown,
): MockObject => {
mockFnStore["onceImplementations"].unshift(implementation);
mockFnStore["onceImplementations"].push(implementation);
return call as MockObject;
};

/** Sets a mock function what return specific value to be called only once.
* This takes precedence over the default mock function.
* Follow the FIFO.
*
* @param value
* @returns
*/
const onceReturnValue = (value: unknown): MockObject => {
mockFnStore["onceImplementations"].push(() => value);
return call as MockObject;
};

Expand All @@ -81,6 +93,7 @@ function fn(
defaultImplementation,
defaultReturnValue,
onceImplementation,
onceReturnValue,
}).reduce(
(acc, [key, value]) => ({
...acc,
Expand Down
24 changes: 22 additions & 2 deletions mock/fn_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ Deno.test("onceImplementation should call only one time", () => {
assertEquals(onceImplementation.mock.calls.length, 1);
mockObject();
assertEquals(onceImplementation.mock.calls.length, 1);

const mock = fn().onceImplementation(() => 1).onceImplementation(() => 2);

assertEquals(mock(), 1);
assertEquals(mock(), 2);
assertEquals(mock(), undefined);
});

Deno.test("onceImplementation should be called in preference to default implementation", () => {
Expand Down Expand Up @@ -162,8 +168,22 @@ Deno.test("defaultReturnValue", () => {
const mockObject = fn();
mockObject.defaultImplementation(() => 2).defaultReturnValue(1);

mockObject();
mockObject(1, 2, 3);

assertEquals(mockObject.mock.calls, [[]]);
assertEquals(mockObject.mock.calls, [[1, 2, 3]]);
assertEquals(mockObject.mock.results, [{ type: "return", value: 1 }]);
});

Deno.test("onceReturnValue", () => {
assertExists(fn().onceReturnValue);
assertEquals(fn().onceReturnValue(1)(), 1);

const mockObject = fn();

mockObject.onceReturnValue(1).onceReturnValue(2).onceImplementation(() => 3);

assertEquals(mockObject(), 1);
assertEquals(mockObject(), 2);
assertEquals(mockObject(), 3);
assertEquals(mockObject(), undefined);
});
1 change: 1 addition & 0 deletions mock/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ interface MockObject<A extends readonly unknown[] = any[], R = unknown> {
onceImplementation(
implementation: (...args: A) => R,
): MockObject<A, R>;
onceReturnValue(value: R): MockObject<A, R>;
}

/** mock result store */
Expand Down

0 comments on commit 53c1e9f

Please sign in to comment.