How to test a function composition with side effects without using mocks?

Viewed 133

I have a function, MyComposedFunction, which is the function composition of 3 functions the second function, fn2, performs a POST request (a side effect) using the result of fn1 and passes this value to fn3.

const fn2 = async (fn1Result) => {
    const result = await fetch(fn1Result.url, fn1Result.payload);

    // some business logic

   return fn2Results;
};

const MyComposedFunction = compose(fn3, fn2, fn1);

// My Test
expect(MyComposedFunction('hello world')).toBe('expected result');

I'd like to avoid writing unit tests for fn3, fn2, and fn1 and instead only test MyComposedFunction. My rationale is that it should not matter whether MyComposedFunction uses compose(...) or is one long giant function as long as MyComposedFunction works.

Is it possible to write a test for MyComposedFunction without having to mock fn2?

I would think that this must be a relatively common situation when trying to do functional programming in JavaScript but haven't been able to find a helpful resource so far.

1 Answers

You can dependency inject fetch into your function like so

const fn2Thunk = (fetcher = fetch) => async (fn1Result) => {
    const result = await fetcher(fn1Result.url, fn1Result.payload);

    // some business logic

   return fn2Results;
};

const fetchMock = async () => ({ result: "blah" })
const MyComposedFunctionTest = compose(fn3, fn2Thunk(fetchMock), fn1);

// My Test
const result = await MyComposedFunctionTest('hello world')
expect(result).toBe('expected result');
Related