Jest came across a token from nestjs that it did not expect

I've hit a roadblock with running my end-to-end tests in Nest.js using Jest. Every time I attempt to execute my e2e test, an error keeps popping up

Jest encountered an unexpected token

Even though all other test suites ran smoothly, this particular one fails consistently. Despite extensive online research, I haven't been able to resolve the issue.

Below is the jest configuration in my package.json file

"jest": {
    "preset": "ts-jest",
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": "(?<!.e2e).spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }

The following snippet shows the content of my tsconfig.json file

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2019",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "esModuleInterop": true,
    "lib": ["es2019"]
  }
}

Note: I am utilizing ts-jest instead of Babel

To run my e2e test, I use the following script from my package.json file

"test:e2e": "jest --config ./test/jest-e2e.json",
and below is the configuration contained in my jest-e2e.json file

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": "../",
  "testEnvironment": "node",
  "testRegex": ".e2e.spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  }
}

Finally, here's the exact error message displayed in the console:

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:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • 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:

    /Users/michaelowolabi/Desktop/YoungM/sz/sz-graphql-api/node_modules/graphql-moment/lib/factory.coffee:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){{GraphQLScalarType} = require 'graphql'
                                                                                                                 ^

    SyntaxError: Unexpected token '='

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (node_modules/graphql-moment/index.js:2:17)

Answer №1

It appears that the graphql-moment code is not in a compatible format for Jest to parse. To resolve this, you can either mock it in your tests like shown below:

jest.mock('graphql-moment', () => ({
  GraphQLDate: jest.fn(),
  ...etcOtherFunctionsFromTheLib
}));

Alternatively, you can instruct Jest to transpile the dependency code during runtime by adding this to your Jest configuration:

transformIgnorePatterns: [
    '<rootDir>/node_modules/(?!graphql-moment)',
],

The second solution may be preferred if you are testing specific date/time expectations.

If you notice that the code is still not being transpired, consider raising an issue with the library maintainers:

https://github.com/jiexi/graphql-moment/blob/master/index.js

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating the NestJS @Get() Decorator: A Comprehensive Guide

The code snippet above demonstrates the functionality of accessing two different functions using URLs like http://localhost:3000/vehicle/availableVehicles and http://localhost:3000/vehicle/1. Both functions work properly in this setup. @Controller(&apo ...

In Angular Google Maps, here's a step-by-step guide on how to zoom in

I am currently utilizing agm/core to showcase the coordinates of a map. Here is the code snippet I am using: <agm-map [latitude]="10.3207886" [longitude]="123.90250049999997"> <agm-marker [latitude]="10.3207886 [longitude]="123.90250049999997 ...

Managing dependencies and automating setup processes can be tricky when incorporating Typescript into a

Query: How can I easily set up Typescript with Symfony without making extensive changes to Symphony's configuration files? Here are the key requirements for the solution: Typescript MVC Pattern should be set up in a private typescript directory: ...

Validating a field conditionally upon submission

Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set. Initializing the form. constructor(){ this.poeForm = this.fb.group({ imageString: [""], imageFileNam ...

The function res.status is not defined

Currently, I am in the process of integrating my upcoming app with Google Sheets. I have relocated the function that manages the post request to "app/api/sheets" as per the recommended documentation. import type { NextApiRequest, NextApiResponse } from &ap ...

Differences between FirebaseFirestore.Timestamp and firebase.firestore.Timestamp in a React Native client and Admin Node server context

Currently facing an issue that seems straightforward but is proving difficult to resolve. Despite thorough documentation review and a lack of similar inquiries, I am encountering difficulties. My project involves building an app using React Native, where ...

Maintain the specific type based on the provided data, rather than the default value, when a related generic is defined

When it comes to unit tests, I prefer a more flexible approach with dynamic generic types that eliminate the need for type casting. I want T to be open-ended, but if I specify a type, I expect to receive an exact match. For R, I need it to precisely matc ...

What is the best way to calculate the product of decimal numbers within a TypeScript Number variable?

Imagine you have a number, for example 288.65, and you want to multiply it without the decimal point in order to obtain the result of 28865. However, when attempting to achieve this by using console.log(288.65 * 100), the output is not as expected, showin ...

What is the functionality of observable in Angular? The 'includes' property is not present in the 'Observable' type

I am currently diving into the world of Angular5 and I have been using Firebase to fetch data for my page display. While researching how to retrieve data from Firebase using AngularFire, I found that many examples were outdated. Eventually, I learned that ...

Encountering an "Unexpected token" error when importing a JSON file in TypeScript even though the JSON is valid

I recently read an article on Hacker Noon about importing JSON into TypeScript, and decided to give it a try in my code. Here's the import line I used: import data from './assets/fonts/helvetiker_bold.typeface.json'; To test if the import ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

Include type annotations for property value shorthand

MergedObject is a container that can store multiple MyClass instances as key-value pairs, where the key represents the variable name (e.g. Obj1) and the value is the corresponding MyClass instance. How can I define a type annotation for MergedObject? cla ...

Utilizing Enum Lowercase as Index Key Type in TypeScript

Is there a way in TypeScript to use the lower case of an enum as an index key type? I have an enum defined as: export enum NameSet { Taxi = 'Taxi', Bus = 'Bus', Empty = '', } I want to define an object with keys based o ...

Modify the entire WebStorm project to adjust the indentation from 2 spaces to 4 spaces

Is there a method to adjust the indentation of all files within my project simultaneously, rather than having to manually edit each line? When I modify tab and indent spacing settings, it does not affect existing indents and tabs, but instead only applies ...

Exploring the structure of TypeScript types using the Compiler API

Is there a way to extract specific type information directly from the TypeScript compiler using an API method? Here's an example: interface User { id: number name: string } type NameOnly = Pick<User, 'name'> type NameOnlyAliased ...

Utilizing Conditional Aurelia Validation Based on Element's Display Status

Currently, I am in the process of setting up a license subscription form using Aurelia and the Aurelia Validation plugin. Within this form, there is a fieldset dedicated to personal information which contains mostly required fields that are validated by Au ...

Create an Angular material table with expandable rows that become sticky when scrolled past, then automatically unstick once they are no longer in view

Currently, I am working with Angular Material Table v11.1.0 which includes a main row with expandable rows. I want the main row to become sticky once an expandable row is opened and remain sticky while scrolling through the table. My goal is for the main ...

Jest throws an error: require function is not defined

I've been struggling with an issue in Angular for the past 3 days. I'm using [email protected] and [email protected]. I even tried downgrading and testing with LTS versions of node and npm, but I keep encountering the same error. Here ...

There is no such property as formData.delete()

When I am using a FormData object to upload a file, I want to add functionality to delete the file from FormData. However, I encountered an error stating that the delete property does not exist on the FormData object. formData.delete(fileName) Code uplo ...

Angular 2 is having trouble with object dot notation in Typescript and is expecting a semicolon

Hello, I am currently transitioning a project from Angular 1 to TypeScript and Angular 2. One issue I'm facing is getting some property definitions into the Angular 2 component. Below are the property definitions causing trouble: import { Component ...