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

What is the best way to limit the type of the second argument based on the type of the

Within the tutorial Exploring How to Extract Parameter Types from String Literal Types Using TypeScript, a fascinating problem is presented without a solution. function calculate(operation, data) { if (operation === 'add') { return da ...

Filtering strings with the same suffix

Here is a code snippet I am working with: type RouterQuery = keyof AppRouter['_def']['queries']; This code defines the following type: type RouterQuery = "healthz" | "post.all" | "post.byId" | "catego ...

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

The value of type 'string' cannot be assigned to type '"menu" | "selectedMenu" | undefined' as it is not compatible with the specified types

I'm working on creating a multiple select feature using TypeScript, material-ui, and React. I am encountering an error when trying to set MenuProps.variant = 'menu'. The error message reads: "Type '{ variant: string; PaperProps: { styl ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Using TypeScript and Angular to remove properties from an object

My RandomValue class and WeatherForecast class are causing me some trouble. The WeatherForecast class is functioning properly, populating the table with data as expected. However, the RandomValues class/interface appears to be returning a list of objects w ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

What if we had webpack disregard certain syntactic enhancements?

For instance: using optional chaining The application I'm working on is strictly for internal use, and it's specifically optimized for the latest Chrome browser. This means I can take advantage of syntactic sugar without needing to compile it, w ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

What is causing the geolocation heading to remain "null" on Android devices when using Chrome?

Recently, I developed a compact geolocation watch using the following code snippet: navigator.geolocation.watchPosition( this.updateLocation.bind(this), this.errorLocation.bind(this), {enableHighAccuracy: true} ); The function updateLocation ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

Limiting the number of items shown in the dropdown panel of an NgSelect

Currently, I am utilizing Angular ngselect to showcase a dropdown menu with multiple options. However, due to the limited screen space, I need to restrict the number of items visible in the dropdown to about 3, allowing users to scroll through the rest. W ...

Extending the declaration of JavaScript native methods is not possible when using TypeScript

When attempting to enhance the JS native String class by adding a new method, I encounter error TS2339. interface String { transl(): string; } String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'St ...

Using ReactJS with Typescript: attempting to interpret a value as a type error is encountered (TS2749)

Currently, I am working on coding a ReactJS class using Typescript and Material-ui in a .tsx file. In one of the custom components that I have created, I need to establish a reference to another component used within this custom component. export class My ...

The subcategory was not factored into my npm package

In my npm module 'ldap-pool', I'm facing an issue where the '@types/ldapjs' package, which is a dependency along with 'ldapjs', does not get installed when I add 'ldap-pool' to another project. This particular s ...

Steps for updating the same array in TypeScript

I have written a reducer code where I check if the same value is already present in the array. If it is, I update the previous value instead of pushing the same value again. Here is my code snippet: export function reducer( state: IDeviceState = ...

The never-ending scroll feature in Vue.js

For the component of cards in my project, I am trying to implement infinite scrolling with 3 cards per row. Upon reaching the end of the page, I intend to make an API call for the next page and display the subsequent set of cards. Below is my implementatio ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

Strategies for displaying error messages in case of zero search results

I am currently developing a note-taking application and facing an issue with displaying error messages. The error message is being shown even when there are no search results, which is not the intended behavior. Can someone help me identify what I am doing ...

Identify when the Vue page changes and execute the appropriate function

Issue with Map Focus Within my application, there are two main tabs - Home and Map. The map functionality is implemented using OpenLayers. When navigating from the Home tab to the Map tab, a specific feature on the map should be focused on. However, if th ...