When using TypeScript with Jest or Mocha, an issue arises where the testing frameworks are unable to read JavaScript dependencies properly, resulting in an error message saying "unexpected token

Currently, I am conducting testing on a TypeScript file using Mocha. Within the file, there is a dependency that I access via the import statement, and the function I need to test resides within the same file as shown below:

import { Foo } from 'foo-library';

// The function I am attempting to test
export const myHelperFunction = (a, b) => {
  return a + b;
  // Foo not utilized
};

export class BigClass {
  public doStuff() {
    // utilizes the Foo dependency
  }
}

In addition to the main file, I have created a test file which looks like this:

import { myHelperFunction } from './my-file';

it('executes correctly', () => {
    expect(myHelperFunction(2, 3)).to.equal(5);
});

During the execution of tests, Mocha encounters an issue where it tries to interpret the contents of foo-library, resulting in an error message stating "unexpected token import," even though the imported module is not directly used within myHelperFunction. This problem arises because the file is in ES6 format, causing Mocha/Node difficulties in parsing it accurately.

One potential solution would involve transpiling the dependency files to ES5. Alternatively, is there a way to bypass importing altogether during the testing process? Attempts to mock the imports using various libraries (such as Sinon) have proven unsuccessful so far.

If anyone has any innovative ideas or suggestions, I would greatly appreciate your input.

Answer №1

If you're looking to address the initial inquiry, consider executing the following command:

mocha -r ts-node/register src/**/test.ts
. Keep in mind that Mocha does not automatically run TypeScript files, so utilizing ts-node/register is necessary to run them as TypeScript files.

Answer №2

Issue resolved by transitioning to Jest.

Although, encountered obstacles with Jest as well. The main problem was the lack of transpilation for JavaScript files in node_modules directory. Find the correct configuration below.

package.json

{
  "name": "myApp",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "start": "ionic-app-scripts serve",
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "test": "jest"
  },
  // rest of dependencies and devDependencies remain unchanged
}

babel.config.js

'use strict';

module.exports = {
    presets: ['@babel/preset-env'],
}

jest.config.js

module.exports = {
  "roots": [
    "<rootDir>/src"
  ],
  "transform": {
    "^.+\\.tsx?$": "ts-jest",
    "^.+\\.js?$": "babel-jest" // additional line that had to be included
  },
  "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "jsx",
    "json",
    "node"
  ],
  "moduleDirectories": [
    "node_modules",
    "src"
  ],
  "transformIgnorePatterns": [
    "node_modules/(?!(@ionic-native)/)" // extra line added to resolve issue
  ]
}

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

react-hook-form replaces the onChange function causing delays in updating the value

Recently, I created a unique Select component utilizing useState and onChange. I attempted to integrate this custom component with the powerful react-hook-form. Allow me to share the code snippet for the bespoke Select component. const Select = forwardRef ...

Ways to expand a TypeScript interface and make it complete

I'm striving to achieve the following: interface Partials { readonly start?: number; readonly end?: number; } interface NotPartials extends Partials /* integrate Unpartialing in some way */ { readonly somewhere: number; } In this case, NotPar ...

Currently, I am collaborating on an e-commerce endeavor utilizing TypeScript and sanity.io, encountering an issue along the way

Encountering an Uncaught TypeError message: Cannot read properties of undefined (reading '_ref'). While attempting to utilize code for displaying API content on a webpage, what might be causing this issue and how can it be resolved to successful ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...

Return a potential undefined output

I am working with a variable called root which could potentially be undefined. Its value is only determined at runtime. const root = resolvedRoot || await this.fileSystem.getCurrentUserHome(); console.log('root.uri = ' + root.uri); The existenc ...

Developing Angular dynamic components recursively can enhance the flexibility and inter

My goal is to construct a flexible component based on a Config. This component will parse the config recursively and generate the necessary components. However, an issue arises where the ngAfterViewInit() method is only being called twice. @Component({ ...

Enhance your Vuex action types in Typescript by adding new actions or extending existing

I'm new to Typescript and I'm exploring ways to add specific type structure to all Actions declared in Vue store without repeating them in every Vuex module file. For instance, instead of manually defining types for each action in every store fi ...

Troubleshooting Next.js Route Redirect Failure to Origin URL

I'm currently facing a challenge in my Next.js project where I have a layout component nested inside the app directory. Within this layout component, there's a client-side navbar component that includes a logout button. The goal is to redirect th ...

How can the Calendar Ant Design showcase events that have fluctuating dates?

Seeking a solution to display events on an Ant Design Calendar using dateCellRender with dates stored in a variable object. Here's an example of the object: [ { "id": 1, "content": "Example", & ...

Is a custom test required for PartiallyRequired<SomeType>?

Is there a way to create a function that validates specific fields as required on a particular type? The IFinancingModel includes the property statusDetails, which could potentially be undefined in a valid financing scenario, making the use of Required< ...

Leveraging keyboard input for authentication in Angular

Would it be possible to modify a button so that instead of just clicking on it, users could also enter a secret passphrase on the keyboard to navigate to the next page in Angular? For example, typing "nextpage" would take them to the next page. If you&apo ...

Convert all key types into arrays of that key type using a TypeScript utility type

My interface (type) is currently defined as: interface User { name: string, id: string, age: number, town: string } I have a function now that will search for Users based on specific fields. I prefer not to manually declare an additi ...

Retrieving the returned value from an Observable of any type in Angular Typescript (Firebase)

I am working on retrieving data from my Firebase User List using the following code: currentUserRef: AngularFireList<any> currentUser: Observable<any>; var user = firebase.auth().currentUser; this.currentUserRef = this.af.list('usuarios ...

Using a union type annotation when passing into knex will result in the return of an unspecified

Knex version: 2.5.1 Database + version: postgres15 When passing a union typescript definition into knex as a type annotation, it returns the type any. However, by using type assertion as UserRecord, we can obtain the correct UserRecord type. It is my un ...

Utilizing history in React with Typescript: A step-by-step guide

I am currently working on a function that navigates to My Page upon clicking a button. However, I encountered an error when trying to implement it in Typescript instead of JavaScript. I am seeking assistance to resolve this issue. //Topbar.tsx function Top ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

The behavior of Task changes when an OperationCanceledException is thrown compared to Task<T>

What is causing the discrepancy in status between t1 and t2 in this failing test scenario? Upon closer inspection, the main difference seems to be that t1 is a simple Task, while t2 is a generic Task<int>. Surprisingly, t2 ends up in a Faulted s ...

What is the best way to execute TypeScript programs on an Android device?

Is there a way to execute TypeScript programs on an Android phone? Are there any offline apps specifically designed for running TypeScript programs on Android devices? ...