Running Jest tests with TypeScript involves executing the tests twice: once for TypeScript files and once for JavaScript files

I’ve recently started writing tests using TypeScript and Jest, but I’m running into an issue where the tests are being executed twice – once for the TS files and then again for the compiled JS files.

While the TypeScript tests are passing without any issues, the JavaScript tests are failing.

yarn run v1.5.1
$ jest
 PASS  src/__tests__/some.test.ts (7.955s)
  ● Console

    console.log src/lib/google-analytics/ga-api.ts:75
      Success!!
    console.log src/__tests__/some.test.ts:42
      { reports: { batchGet: [Function: batchGet] } }

 FAIL  dist/__tests__/some.test.js
  ● Console

    console.log dist/lib/google-analytics/ga-api.js:64
      Reject

  ● it gets a full google analytics report

    No key or keyFile set.

... (Error stack trace details)

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        9.516s
Ran all test suites.
error An unexpected error occurred: "Command failed.
Exit code: 1
Command: sh
Arguments: -c jest
Directory: /Users/carlosbernal/Documents/Grability/DataScience/ga-downloader
Output:
".
info If you think this is a bug, please open a bug report with the information provided in "/Users/carlosbernal/Documents/Grability/DataScience/ga-downloader/yarn-error.log".
info Visit https://yarnpg.com/en/docs/cli/run for documentation about this command.

Is this behavior normal with ts-jest or am I overlooking some additional configuration settings?

Answer №1

Is it possible that I need to adjust configuration settings for ts-jest?

It is recommended to specifically set roots to /src. You can find a helpful configuration here:

module.exports = {
  "roots": [
    "<rootDir>/src"
  ],
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  },
  "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "json"
  ],
}

It is also worth noting that only .tsx? files are being tested (no .jsx?) ;)

Answer №2

Encountered a similar problem while working with AWS CDK in Typescript. To resolve it, I made a simple adjustment by including .js in the testPathIgnorePatterns property within jest-config.js:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testPathIgnorePatterns: [".d.ts", ".js"]
};

Answer №3

If you are utilizing an IDE, consider turning off the automatic conversion from .ts to .js to prevent any errors caused by the generated .js file.

For those using IntelliJ/Webstorm: Navigate to Preferences | Languages & Frameworks | TypeScript, and uncheck the option for Recompile on changes.

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

The beforePopState event in next/router is not triggering as expected

Noticing an issue where the beforePopState event is not triggering when I use the back button. This code snippet is part of a hook defined in _app.js according to the documentation. The current version being used is 12.1.5 If anyone has insights on what ...

Guidance on showcasing the current day's weekday name through TypeScript

I am perplexed about how to begin in TypeScript after successfully setting up the display using gate. ...

How can I assign two different colors based on the type in Typescript?

I am configuring a color property based on the nature of the display. colorStyle: { textAlign: "center", backgroundColor: "transparent", color: (theme.colors.BaseColor.Red as any).Red4, } The cu ...

I require the ability to modify cellEditor parameters in real-time

How can a value be passed to cellEditorParams after the user double clicks on a grid row? The application triggers a service call on row click and the response needs to be sent to cellEditorParams. ...

Adding a new document to an existing collection with an array field in MongoDB

Having an issue with adding a new chapter to my var array. Here is the code snippet in question: array.push({ chapter: [ { id: 2, title: 'adsf', content: &ap ...

Troubleshooting Angular2 Error: Incompatibility with TypeScript - Unable to Assign String

While working on creating a custom pipe in Angular2 for filtering, I encountered the following build error: Error TS2322: Build: Type '() => string' is not assignable to type 'string' Below is my sample code: import { PipeTransf ...

Encountering a problem with Typescript and eslint while utilizing styled-components and Material UI: "Warning: React does not identify the `showText` prop on a DOM element."

While using a styled component to return a material ui Fab component, an error appears in the console: React does not recognize the `showText` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as low ...

Develop a JSON parsing function for VUE reusability

Currently, I am iterating through an array in Vue that contains objects with strings nested within. These objects have various properties such as idType, type, user, visibility, seller, product, company, and additionalData. notifications: [ 0: { idTy ...

Modifying a property in a nested layout through a page in Next.js 13

Currently, I am facing a challenge in updating the page title within a nested layout structure. app/docs/layout.tsx: export const DocsLayout = ({children}:{children: React.ReactNode}) => { return ( <> <header> ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

Error code -8 occurred while executing the yarn dev command, unable to identify the issue

I'm facing an issue with my development script that is structured like this: "scripts": { "dev": "./test.sh", }, Upon running the 'yarn dev' command, I encounter the following error message: Internal Error: ...

What is causing the undefined value for the http used in this function?

My Code Component import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app-root', template: '<button id="testBtn"></button>' }) export c ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

RC6 - What is the significance of encountering an 'Unexpected token <' error message?

After updating to RC.6, I am encountering a series of errors related to third-party components. Specifically, the error message displayed is: SyntaxError: Unexpected token <. This issue has arisen with ng2-bootstrap, ng2-select, and angular2-jwt. Howev ...

Ensure that the specified Class type must have a constructor with no arguments

When working with a function that takes a parameter representing a Class (not an object or instance, but the Class itself), or essentially a variable assigned to a Class. The challenge is ensuring that the Class assigned to the parameter has a constructor ...

The state object in Redux Toolkit remains static, resulting in the error message "Uncaught TypeError: Cannot assign to read only property 'property-name' of object '#<Object>'"

I'm facing an issue where I am trying to update the data of a state object in Redux Toolkit but it's not changing, and instead throwing an error that says Uncaught TypeError: Cannot assign to read only property 'status' of object ' ...

What is the process of creating the /dist folder in an unreleased version of an npm package?

Currently working on implementing a pull request for this module: https://github.com/echoulen/react-pull-to-refresh ... It seems that the published module generates the /dist folder in the package.json prepublish npm script. I have my local version of the ...

What does it signify when it is stated that "it is not a descendant of the indexer"?

Currently, I am diving into Typescript with the help of this informative guide on indexer types. There is a specific piece of code that has me puzzled: interface NumberDictionary { [index: string]: number; length: number; // okay, length shoul ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

What is the best way to overload a function based on the shape of the argument object in

If I am looking to verify the length of a string in two different ways (either fixed or within a specific range), I can do so using the following examples: /* Fixed check */ check('abc', {length: 1}); // false check('abc', {length: 3}) ...