jeudi 12 avril 2018

Best practice to Unit Test a module that depends on the result of several calls to the same function

I want to test, in the most isolated way possible, that a function that I have, returns a sorted array, the function that I have has the shape:

import factoryishFunction from './someModule'
import { times } from 'ramda';

export function generateArrayWith(nonDeterministicFunction, deterministicFunction, sizeOfArray) {
return times(factoryishFunction(nonDetermisticFunction, deterministicFunction), sizeOfArray)
.sort((a, b) => (a.value< b.value? 1 : -1)) }

So basically I call times that calls a function n times and put the results in an array. Then I call this factoryishFunction that using the other passed functions returns an object with attribute value, and then I sort by value in descendant order.

In my understanding, since factoryishFunction is doing other stuff to give me back my value, I should mock it up in my test in order to have a really isolated unit test.

Since the result of factoryishFunction depend on the functions that I pass to generateArrayWith, my doubt is, what is the best way of writing a test where I am not involving the factoryishFunction behaviour.

For example I have:

    import generateArrayWith from '../ItsModule';
import factoryishFunctionMock from '../someModule';

jest.mock('../someModule');

beforeAll(() => {
    factoryishFunctionMock .mockClear();
});
describe('My module', () => {
        it('returns the values sorted', () => {
            factoryishFunctionMock .mockImplementation((() => {
                let value = 0;
                return () => ({value: value++});
            })); // Each call in the mockedImplementation will return a different value from zero and up
            const noop = () => {};
            const actual = generateArrayWith(noop, noop, 3);

            expect(actual).toEqual([{value: 2},{value: 1},{value: 0},]);
        });
});

But I feel that by passing noop to the generateArrayWith I shouldn't be able to assert those values since they depend on the passed functions. How could I do this in a better way?

Aucun commentaire:

Enregistrer un commentaire