0

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?

3
  • number = 222, len=3 Commented Sep 25, 2019 at 8:24
  • seems testing isn't really what you are after, but rather debugging :) Commented Sep 25, 2019 at 8:28
  • No, no - I am only trying to write arabic to roman function using TDD... ;) Commented Sep 25, 2019 at 8:29

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.