jundymek
jundymek

Reputation: 1043

Test variable inside function (jestjs)

Is it possible to test simple variable inside function? I would like to test only part of my function. For example

function x(number) {
   let len = number.toString().length
   return 'End'
}

I would like to test if len variable is set properly. Is it possible?

Upvotes: 0

Views: 1858

Answers (1)

Harmenx
Harmenx

Reputation: 946

It is not possible to write assertions for the private internals of js functions.

I've personally found this barrier to encourage better tests to be written. The existing tests continue to enforce that internal changes work correctly.

Writing tests against internal function behavior increases the maintenance effort of the code being tested. Since the tests become more tightly coupled to the source code, they'll need more attention when making changes.

If you find yourself wanting to test some internal behavior, it's recommended to create another function. For example

export class Math extends React.Component {
    ...

    computeLen(input) {
        return input.toString().length;
    }

    function x(number) {
     let len = computeLen(number)
     return 'End'
   }
}

You can now assert that whatever logic is being used to calculate the sample length works as expected for various inputs. This extraction of logic often makes the function x(number) more readable as well.

Upvotes: 4

Related Questions