Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest- testing variables inside component methods

Let's say I have a class component that has something like this:

export class Math extends React.Component {
    ...
    someComponentMethod = numb => {
        const sample = numb * 10 
        ...
        const result = numb -5
        return result
    }

Is it possible to make test assertions on sample variable in Jest?

like image 546
Alejandro Avatar asked Feb 05 '18 05:02

Alejandro


1 Answers

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

I've personally found this barrier to encourage better tests to be written. By testing only the public API for correctness, you have the ability to refactor internals without having to update any tests. The existing tests continue to enforce that internal changes work correctly.

Writing tests against internal behavior easily 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. This can also degrade the reliability of the tests, since more changes to the tests increases the likelihood of bugs manifesting in the tests themselves.

If you find yourself wanting to test some internal behavior, it might be a good time to extract some functionality. In your example, the sample value calculation could be extracted into a pure function of its own:

export class Math extends React.Component {
    ...

    computeSampleValue(input) {
        return input * 10
    }

    someComponentMethod = numb => {
        const sample = this.computeSampleValue(numb)
        ...
        const result = numb -5
        return result
    }
}

You can now assert that whatever logic is being used to calculate the sample value works as expected for various inputs. This extraction of logic often makes someComponentMethod more readable as well.

If you absolutely need to test some other internal behavior and are aware of the increased code debt, you can have your method perform side effects and write assertions for those. For example, instead of defining sample as a function-scope variable, create a this.sample property on the component instance and update that. In a test you then call the target method, and afterwards assert that componentInstance.sample was changed as expected.

like image 146
Caleb Miller Avatar answered Oct 31 '22 09:10

Caleb Miller