Having trouble configuring Jest for TypeScript integration

I am currently implementing unit testing for a typescript project following the guidelines in this example: https://dev.to/muhajirdev/unit-testing-with-typescript-and-jest-2gln

In my project, I have a file named main.ts that exports an isInternalLink function.

Furthermore, there is a main.spec.ts file where I attempt to test the function. However, I encounter the following error:

C:\data\devel\apps\tmp\jest-typescript\src\main.spec.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { isInternalLink } from './main.js';
SyntaxError: Unexpected token {
  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)

To access the complete example code, you can visit the public repository here:

If anyone has insights on resolving this issue or has a working example to share, I would greatly appreciate it.

Answer №1

The Jest TypeScript guidance includes information on utilizing babel for preprocessing TypeScript files, as well as references to ts-jest.

To incorporate ts-jest into your project, simply install ts-jest:

npm install --save-dev ts-jest

and add the following snippet to your package.json to preprocess the TypeScript files:

  "jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json"
    ]}

Upon completing these steps in your project setup, you should be able to execute the tests successfully:

$ npx jest
 PASS  src/main.spec.ts
  ✓ should return false given external link (2ms)
  ✓ should return true given internal link

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.096s, estimated 2s
Ran all test suites.

Answer №2

If you want to see a demonstration on how to use jestjs with typescript, check out this link: https://github.com/mrdulin/jest-codelab

Here are the devDependencies listed in the package.json file:

"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"

To set up, create a file named jest.config.js in the root path of your project:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node'
};

Once that's done, refer to the documentation and follow the specified 4 steps outlined here: https://github.com/kulshekhar/ts-jest#getting-started

Answer №3

Encountered an issue where my configuration file was named jest.config.ts. After attempting to run the command:

npx jest --config jest.config.ts
Usage: jest.js [--config=<pathToConfigFile>] [TestPathPattern]
[...]
The --config option requires a JSON string literal, or a file path with a .js or .json extension.
Example usage: jest --config ./jest.config.js

Simply changed the name from jest.config.ts to jest.config.js and it worked smoothly...

--

Received assistance from @shadowspan and @slideshowp2 in resolving this issue, much appreciated!

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

Tips on retrieving enum values in typescript

Having trouble retrieving values from an enum? Check out this snippet of code: export const enum ComplianceType { ENGINEER_ASSESMENT = 'ENGINEER_ASSESMENT', CONSTRUCTION_COMPLIANCE = 'CONSTRUCTION_COMPLIANCE', ARCHITECTURE_ASSIGN ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

I'm struggling to figure out the age calculation in my Angular 2 code. Every time I try to run it,

Can anyone assist me with calculating age from a given date in Angular? I have written the following code but I keep getting undefined in the expected field. This is Component 1 import { Component, OnInit, Input } from '@angular/core'; ...

Retrieve new data upon each screen entry

After running a query and rendering items via the UserList component, I use a button in the UserList to run a mutation for deleting an item. The components are linked, so passing the deleteContact function and using refetch() within it ensures that when a ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

Index.js is dynamically importing a .tsx file post-build, with a specific focus on Windows

While working on my project, I decided to customize a module by cloning it and making some changes. After installing the dependencies and building it, I encountered an error when trying to run it. The error message stated: Error: Unable to resolve module & ...

Unable to execute functions on observable outcomes

Let's discuss an interface called Vehicle, a class named Car that implements it, and a method within the class titled isColorRed: export interface Vehicle{ color : string; } export class Car implements Vehicle{ color : string; constructo ...

How can the value of a number in Angular be changed without altering its original value?

Imagine having the initial number 100. If I enter 50 in another input, it should add 50 to 100. However, if I then change the value from 50 to 80, the total should be 180 and not 230. The goal is always to add numbers to the original sum, not the new valu ...

Steps to customize the color scheme in your Angular application without relying on external libraries

Is there a way to dynamically change the color scheme of an Angular app by clicking a button, without relying on any additional UI libraries? Here's what I'm trying to achieve - I have two files, dark.scss and light.scss, each containing variabl ...

Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more. Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without ...

Issue with Typescript Application not navigating into the node_modules directory

After attempting to load the app from the root directory of our server, it became clear that this was not a practical solution due to the way our application uses pretty URLs. For instance, trying to access a page with a URL like http://www.website.com/mod ...

Accessing a variable from different tabs in an Ionic 3 weather application

I am currently exploring the world of app development and have decided to create a weather application. The main goal of this app is to display the current weather using data from the openweathermap.org API. To achieve this, I have divided my app into 3 ta ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

Issue with vue-class-component: encountering TS2339 error when trying to call a method within

My vuejs application is being built using vue-cli-service. After a successful build, I encountered TS2339 errors in my webstorm IDE: Test.vue: <template> <div>{{method()}}</div> </template> <script lang="ts"> impor ...

Advanced TypeScript deduction

I have a coding query: interface Feline{ purr:boolean } interface Jungle{ lion:Feline, tiger:Feline, leopard:Feline } later in the code: let cats:Jungle;// assume it's properly defined elsewhere for(const j in cats) if(cats.hasOwnProperty(j)){ ...

Create a Typescript React class and define the State type as either an interface or null

When working with React and typescript, it is common to declare state types in the following manner: import * as React from "react" interface IState { someState: string } class MyClass extends React.Component<{}, IState> { state = { someSt ...

leveraging two connected hooks

I am facing a challenge where I need to utilize two hooks that are interdependent: useHook1() provides a list of ids, and useHook2(id) is called for each id to retrieve a corresponding name. Essentially, what I aim to achieve is: const [allData, setData] ...

The Vue Typescript callback is automatically assigned the type "any" when not explicitly defined

Encountering a TypeScript compiler error while using an anonymous function with lodash debounce in my Vue component's watch option. The error states: "this implicitly has type any." Below is the code snippet of my component: export default defineComp ...

Creating composite type guards - passing down properties from the type guard to the calling function

type Bird = { fly: () => "fly" }; type Insect = { annoy: () => "annoy" }; type Dog = { beTheBest: () => "dogdogdog" }; type Animal = Bird | Insect | Dog; const isBird = (animal: Animal): animal is Bird => { if ...

There seems to be a problem fetching the WordPress menus in TypeScript with React and Next

Recently I've started working on a project using React with TypeScript, but seems like I'm making some mistake. When trying to type the code, I encounter the error message: "TypeError: Cannot read property 'map' of undefined". import Re ...