Ways to directly test an internal function

Asked

Viewed 36 times

0

Suppose we have the following closure function and would like to test the internal function with Jest.

First-hand closure function made by me:

function ModuleCharacterCounter() {   

    function characteCounter(nome) {
        return `O nome ${nome} possui ${count(nome)} letras`;  
    }  

    function count(nome) {     
        return nome.length;  
    }

    return {     
        start(nome) {
            return characteCounter(nome);
        }    
    };
    
}

var counter = ModuleCharacterCounter();
console.log(counter.start('José'));

Studying the documentation I found that I can test the module with Jest, but nothing like testing private functions.

**Testing of the module:**

let {ModuleCharacterCounter} = require('../arquivo.js')

describe("Character Counter", () => {
    test("testantdo", () => {
        let counter = ModuleCharacterCounter();
        expect(counter.start('José')).toEqual( "O nome José possui 4 letras");
    });
});

Unconvinced I turned github and found this repository https://github.com/bahmutov/test-mole 7 years ago. With a little more code, I was able to test the internal function.

Internal function test:

if (typeof require === 'function') {
    require('test-mole');
    require('lazy-ass');
}

(function ModuleCharacterCounter() {   

    function characteCounter(nome) {
        return `O nome ${nome} possui ${count(nome)} letras`;  
    }

    function count(nome) {     
        return nome.length;  
    }

    testMole.it('Testando função count', function () {
        lazyAss(count('José'), 4);
    });

    return {     
        start(nome) {
            return characteCounter(nome);
        }    
    };
    
}());

Finally, are there alternatives to soft test? It is possible to test internal function with jest, or was I the one who did not understand the documentation?

  • The title is Ways to directly test an internal function and in the question you speak of closure, and from what I understand, you want to test an internal function that’s a direct closure on the outside, that’s right?

  • Yes, correct me if I’m wrong, but I think closure in case would be a function(type of a module) that encapsulates, making some internal private functions, is not?

1 answer

1

I believe that the question here is a little lower hole, perhaps the reflection "Should I test my private methods?". In theory, my opinion is that you should not, because you are testing it indirectly by the public part, if it is not, that code is unusable/not covered. In your case for example it is being covered by the call to the public method.

Here are some links on the issue https://stackoverflow.com/a/34586/10880357 https://stackoverflow.com/a/52054/10880357

Browser other questions tagged

You are not signed in. Login or sign up in order to post.