0

As the title says, why i can't call Example.method2()?

Example class:

class Example {
  private method1(): any{
    return "it works"
  }
  #method2(): any {
    return "it works"
  }
}

Test that works

it('should call method1', () => {
    // @ts-ignore
    const result = Example.method1()

    expect(result === "it works" ).toBeTruthy(); // OK

  });

Test that should work

it('should call #method2', () => {
    // @ts-ignore
    const result = Example.#method2()

    expect(result === "it works" ).toBeTruthy(); // NOT OK

  });

Error log:

        const result = Example..call(Example);
                               ^

    SyntaxError: Unexpected token '.'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
addUsername
  • 183
  • 1
  • 12
  • The point of private is to not be accessible. What is that test even supposed to do other than just fail? – VLAZ Jan 02 '23 at 15:26
  • the test should test the logic inside a private method. I know that the logic should be extracted to a class and be tested there BUT, this is not something related to the question. I'd like to know what changes between "#" and "private" that makes the second test fail – addUsername Jan 02 '23 at 15:31
  • 1
    Again, private methods are *inaccessible*. Because, again, that's what private is. The test cannot work. This error might just be down to the way the code is transpiled. And it might just be a reflection of the invalid code. – VLAZ Jan 02 '23 at 15:35
  • 1
    This article may help: https://www.amitmerchant.com/typescript-private-modifier-vs-ecmascript-hash-private-fields/ – Linda Paiste Jan 02 '23 at 15:41
  • Thanks, the solution is here https://stackoverflow.com/a/59712324/13771772, so "#" makes the method truly private – addUsername Jan 02 '23 at 15:44
  • I voted to close but now I'm reconsidering. The answer is this: Neither test *"should"* work because you are testing a private method which *should* be inaccessible outside of the class. The TS `private` *does* work at runtime because the `private` keyword is "syntactic sugar" which is only enforced at compile-time. The ECMAScript `#` will make the method private and inaccessible at both runtime and compile-time. – Linda Paiste Jan 02 '23 at 15:46

0 Answers0