jeudi 26 décembre 2019

Jest: Testing imported module to call another function that returns a function that is then tested

This one seems like a bit of a brain teaser but lets give it a shot! So I am testing a function that calls a function from a module that then returns a function that I then need to test. I know this is a bit convoluted. I was thinking of splitting it apart but the testing all parts from one actually makes a lot of sense in this case because of its helper function nature. So let's begin:

Spec:

import { functionToTest } from './moduleToTest';

describe('helper function' , () => {
    it('should call the function_Returning_Object_WithFunction().THE_REAL_FUNCTION_TO_TEST with the value that I have in this spec sheet', () => {
        expect(function_Returning_Object_WithFunction().THE_REAL_FUNCTION_TO_TEST) // expectation
    });
});

moduleToTest:

import { function_Returning_Object_WithFunction } from './module_for_this'

export const functionToTest = (value) => {
    if (function_Returning_Object_WithFunction().THE_REAL_FUNCTION_TO_TEST) {
        function_Returning_Object_WithFunction().THE_REAL_FUNCTION_TO_TEST('string', {
            someKey: someValueToTestWasPassed
        }
    }
}

So what happens:

  1. Helper function called a function that returns an object
  2. That object has a function that needs to be called with a specific value passed down

I am not exactly sure where to begin. I have tried stubbing the first function that is called and returning an object that has the function acting as a spy but that doesn't work I get a "function_Returning_Object_WithFunction() is a read-only function" error.

Please let me know if I can clarify I know this can be difficult with so many layers.

Aucun commentaire:

Enregistrer un commentaire