One cannot write assertions for the private workings of functions.
I have personally found this limitation beneficial in promoting the creation of better tests. By focusing on testing only the public API for accuracy, developers can freely refactor internal components without needing to modify existing tests. The current tests continue to validate that any changes to internals function correctly.
Testing internal behavior can significantly increase the maintenance effort required for the tested code. Due to the close connection between the tests and the source code, they become more intricate when modifications are made. This heightened complexity can decrease the reliability of the tests as frequent alterations raise the risk of introducing bugs into the test cases themselves.
If there is a need to evaluate some internal behavior, it might be an opportune moment to extract certain functionality. For instance, the calculation of the sample
value could be separated into its own standalone pure function:
export class Math extends React.Component {
...
computeSampleValue(input) {
return input * 10
}
someComponentMethod = numb => {
const sample = this.computeSampleValue(numb)
...
const result = numb -5
return result
}
}
This separation allows for asserting that the process used to determine the sample
value functions properly across different inputs. Moreover, extracting logic like this often enhances the readability of the someComponentMethod
.
If there is a necessity to examine other internal behaviors despite the additional coding burden, one approach would be to have the method trigger side effects and then verify those through assertions. For example, instead of defining sample
as a variable within the function scope, create a this.sample
property on the component instance and update it accordingly. In a test scenario, execute the target method and subsequently confirm that componentInstance.sample
reflects the expected changes.