Skip to content

TypeScript: decorators do not work with abstract classes #6225

Closed
@StragaSevera

Description

@StragaSevera

Is this a bug report?

Yes.

Did you try recovering your dependencies?

Yes.

yarn --version
1.13.0

Which terms did you search for in User Guide?

"Typescript decorators abstract classes".

Environment

Environment Info:

  System:
    OS: Linux 4.20 Arch Linux undefined
    CPU: x64 Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz
  Binaries:
    Node: 11.6.0 - /usr/bin/node
    Yarn: 1.13.0 - /usr/bin/yarn
    npm: 6.5.0 - /usr/bin/npm
  Browsers:
    Firefox: 64.0.2
  npmPackages:
    react: ^16.7.0 => 16.7.0 
    react-dom: ^16.7.0 => 16.7.0 
    react-scripts: 2.1.3 => 2.1.3 
  npmGlobalPackages:
    create-react-app: 1.3.0

Steps to Reproduce

Basically, the problem lies in babel/babel#8172 :

  1. Add a file Bar.ts:
function decorate() {
  return (target: any, propertyKey: string) => {
    console.log(propertyKey);
  };
}

abstract class Foo extends Object {
  @decorate()
  baz: String = "baz";
}

export class Bar extends Foo {}
  1. Add a jest test file tests/Bar.test.ts:
import {Bar} from "../Bar";

it('fails', () => {
    const bar = new Bar();
    expect(bar.baz).toEqual("baz");
});
  1. yarn run test

Expected Behavior

The jest test runs successfully.

Actual Behavior

 FAIL  src/test/Bar.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /home/ought/Coding/Web/Frontend/test-app/src/Bar.ts:24
    let Foo = (_dec = decorate(), (_class = abstract class Foo extends Object {
                                                     ^^^^^

    SyntaxError: Unexpected token class

    > 1 | import {Bar} from "../Bar";
        | ^
      2 | 
      3 | it('fails', () => {
      4 |     const bar = new Bar();

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (src/test/Bar.test.ts:1:1)

Reproducible Demo

https://github.com/StragaSevera/test-app

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions