commadelimited
commadelimited

Reputation: 5119

Jest unit test in Angular app is throwing "Jest encountered an unexpected token" error

I'm receiving email messages from a local mail server and I need to be able to parse them in JavaScript. The @ProtonMail/jsmimeparser library is working flawlessly which is a huge relief. However, it's causing failures in my unit testing. It's not any specific test, but the harness for this particular page. Full error output is below.

Versions:
Angular 18.2.12
Jest 29.7.0
jsmimeparser 3.0.1

Directory tree for the plugin

node_modules/@protontech
└── jsmimeparser
    ├── LICENSE
    ├── README.md
    ├── index.d.ts
    ├── index.js
    ├── lib
    │   ├── headerEmitter.js
    │   ├── headerParser.js
    │   ├── jsmime.js
    │   ├── mailParser.js
    │   ├── rawMimeParser.js
    │   ├── structuredHeaders.js
    │   ├── textDecoders.js
    │   └── utils.js
    └── package.json

Error output:

Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/amatthews/src/WEB/accounts-client/node_modules/@protontech/jsmimeparser/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { parseMail } from './lib/mailParser';
                                                                                      ^^^^^^
    SyntaxError: Unexpected token 'export'

      2 | import { Router, ActivatedRoute } from '@angular/router';
      3 | import { ReplaySubject, Subscription, combineLatest } from 'rxjs';
    > 4 | import { parseMail } from '@protontech/jsmimeparser';
        | ^
      5 | import { EmailMessage } from '../../model/email-message.model';
      6 | import { MailingListsService } from '../../service/mailing-lists.service';
      7 | import { Status } from 'src/app/model/status.model';

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
      at Object.<anonymous> (src/app/mailing-lists/component/message-queue/message-queue.component.ts:4:1)
      at Object.<anonymous> (src/app/mailing-lists/component/message-queue/message-queue.component.spec.ts:3:1)

Sample message body

{
"request_id": "1",
"original_size": 855,
"sender": "[email protected]",
"subject": "Testing one two three",
"hold_date": new Date(),
"msg": "Received: from [127.0.0.1] (localhost [127.0.0.1])\n\t(using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)\n\t key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256)\n\t(No client certificate requested)\n\t(Authenticated sender: [email protected])\n\tby mailman.default.svc.cluster.local (Postfix) with ESMTPSA id A48A33E9849\n\tfor <[email protected]>; Thu, 23 Jan 2025 21:24:11 +0000 (UTC)\nMessage-ID: <[email protected]>\nDate: Thu, 23 Jan 2025 15:24:11 -0600\nMIME-Version: 1.0\nUser-Agent: Mozilla Thunderbird\nContent-Language: en-US\nTo: [email protected]\nFrom: Dev Tester <[email protected]>\nSubject: Testing one two three\nContent-Type: text/plain; charset=UTF-8; format=flowed\nContent-Transfer-Encoding: 7bit\nX-MailFrom: [email protected]\nX-Mailman-Rule-Hits: nonmember-moderation\nX-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; emergency; loop; banned-address; member-moderation\nMessage-ID-Hash: XM4OS47LU7DRYIO74WB5K4W345NPZ37O\nX-Message-ID-Hash: XM4OS47LU7DRYIO74WB5K4W345NPZ37O\n\nThis is a single line message body.\n\n"}

Component

  ...
  ngOnInit() {
    this.mailingService.getHeldMessages('abc-announce').subscribe(
      response => {
        this.messages = (response as EmailMessage[]).map(
          message => {
            message.msg = this.formatMessage(message.msg);
            return message;
          }
        );
      },
    );
  }

  formatMessage(msg: string): string {
    // break message into the distinct parts of a MIME email.
    const email = parseMail(msg);
    return email.body.html;
  }
  ...

Sample unit test

describe('MessageQueueComponent', () => {
  let component: MessageQueueComponent;
  let fixture: ComponentFixture<MessageQueueComponent>;

  beforeEach(async () => {

    TestBed.configureTestingModule({
      imports: [],
      providers:[
        provideHttpClient(),
        provideHttpClientTesting(),
      ],
    })
    .compileComponents();

    fixture = TestBed.createComponent(MessageQueueComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

jest.config.ts

import type {Config} from 'jest';

const config: Config = {
    verbose: true,
    preset: 'jest-preset-angular',
    setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
    moduleNameMapper: {
        '^src/(.*)$': '<rootDir>/src/$1',
        '^app/(.*)$': '<rootDir>/src/app/$1',
        '^assets/(.*)$': '<rootDir>/src/assets/$1',
        '^environments/(.*)$': '<rootDir>/src/environments/$1',
    },
};

export default config;

Upvotes: 0

Views: 176

Answers (2)

Zeros-N-Ones
Zeros-N-Ones

Reputation: 1082

This configuration should resolve the "Unexpected token export" error:

import type { Config } from 'jest';

const config: Config = {
    verbose: true,
    preset: 'jest-preset-angular',
    setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
    moduleNameMapper: {
        '^src/(.*)$': '<rootDir>/src/$1',
        '^app/(.*)$': '<rootDir>/src/app/$1',
        '^assets/(.*)$': '<rootDir>/src/assets/$1',
        '^environments/(.*)$': '<rootDir>/src/environments/$1',
    },
    transformIgnorePatterns: [
        // This line tells Jest to transform the jsmimeparser module
        'node_modules/(?!@protontech/jsmimeparser)'
    ],
    transform: {
        '^.+\\.(ts|js|html)$': [
            'jest-preset-angular',
            {
                tsconfig: '<rootDir>/tsconfig.spec.json',
                stringifyContentPathRegex: '\\.(html|svg)$',
            },
        ],
    },
};

export default config;

Make sure your tsconfig.spec.json includes the necessary compiler options for handling ES modules:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}

Upvotes: 0

Naren Murali
Naren Murali

Reputation: 57986

UPDATE:

The most important change was to configure the transformIgnorePatterns as below:

"transformIgnorePatterns": [
    "/node_modules/@protontech/(?!jsmimeparser).+\\.js$"
],

I recreated a project with angular 19, then changed the jest.config.ts to reflect what was provided in the jest-preset-angular latest documentation.

import type { Config } from 'jest';
import presets from 'jest-preset-angular/presets';

export default {
...presets.createCjsPreset({
    tsconfig: 'tsconfig.spec.json',
}),
setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
    "transformIgnorePatterns": [
        "/node_modules/@protontech/(?!jsmimeparser).+\\.js$"
    ],
} satisfies Config;

Then we can update the setup-jest.ts as below:

import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';
// import './jest-global-mocks';

setupZoneTestEnv();

Also adding tsconfig.spec.json for reference:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "types": ["jest", "node"]
  },
  "files": ["polyfills.ts"],
  "include": ["**/*.spec.ts", "**/*.d.ts"]
}

Github Repo -> npm i --legacy-peer-deps -> npx jest --verbose (You can try your normal test command instead of this)


Seems like you are using a JS file and during conversion (Read as typescript) it is throwing an error, could you try:

import type {Config} from 'jest';

const config: Config = {
    verbose: true,
    preset: 'jest-preset-angular',
    setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
    "transformIgnorePatterns": [
      "node_modules/(?!@protontech)"
    ],
    moduleNameMapper: {
        '^src/(.*)$': '<rootDir>/src/$1',
        '^app/(.*)$': '<rootDir>/src/app/$1',
        '^assets/(.*)$': '<rootDir>/src/assets/$1',
        '^environments/(.*)$': '<rootDir>/src/environments/$1',
    },
};

Jest gives an error: "SyntaxError: Unexpected token export"

Upvotes: 2

Related Questions