testingmethodsjestjsprivateecmascript-2020

ES2020 private class methods/fields and testing


As you may know, ES2020 is introducing private class methods and fields, similar to what we have currently in typescript (albeit a different keyword... TS -> private | JS -> #methodName or #fieldName).

Link to the RC (stage 3): https://github.com/tc39/proposal-private-methods

We can currently use this with a babel plugin: https://babeljs.io/docs/en/babel-plugin-proposal-private-methods

Tech stack:

I work with Jest and Enzyme for unit testing.

The problem:

The issue I'm facing is that whenever I import a class using these fields or methods and I simply try to reference the wrapper.instance() calling them to test them, I can see that the private method is not visible in the instance (which is correct, since it's private).

An example error: #someMethod is undefined

How would you go on approaching this?

Would you skip testing the private methods or is there a solution?


Solution

  • While debugging my UT I saw that they get a prefix to their names of __private_XXX_ when XXX is their "index" of appearance in the class.

    so you can access #someMethod by using __private_XXX_someMethod but that requires you to check that "index" and to update it every time the class changes the indexes.