Is there a way to exclude certain files from compilation in Typescript, but still include them for testing purposes

Organizing Files

In my project, I have structured my files as follows:
functions/lib/src/...src .ts files
functions/lib/test/...test files
functions/tsconfig.json

Initially, including the test files directory in the tsconfig.json.include property allowed linting to work successfully in the test files. However, when running tsc, the test files were also compiled into js.

Upon removing the test directory from the tsconfig.json include property, errors started appearing in the test files related to Jest methods, with messages like:

Cannot find name 'test'. Do you need to install type definitions for a test runner? Try npm i @types/jest or npm i @types/mocha.

This is how the tsconfig.json appears:

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017"
  },
  "compileOnSave": true,
  "include": [
    "src",
  ],

}

And here is the jest.config.js file:

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

How can I ensure that Jest methods are recognized without having the test files compiled?

Answer №1

I found the solution in this helpful article.

To exclude test files from compilation, you need to create a separate tsconfig.build.json file that extends your main tsconfig.json. Here's what the content of the new file should look like:

{
  "extends": "./tsconfig.json",
  // ⬇️ adjust this path based on how you name your test files
  "exclude": [
    "lib/test/*"
  ]
}

After setting up the build configuration, you can use the following command to transpile your code without including test files:

tsc --project tsconfig.build.json

Don't forget to add this command as a script in your package.json for easy access during the build process.

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 'ReactNode' binding element is automatically assigned an 'any' type

Just started a new project using create-react-app app --template typescript. In the src/components/MyButton/MyButton.tsx file, I have the following code: import React, { ReactNode } from "react"; const MyButton = ({ children: ReactNode }) => ...

I attempted to mock a standalone class method using jest.spyOn, but unexpectedly the real method was executed instead of the mock implementation

Programming Class //Class Definition class User { constructor(){ } getUserData(){ //performs an action without returning anything } } When a button is clicked within a react component, this method gets executed //ReactComponent.tsx handleButtonClick() { ...

Utilizing properties in a fresh function with Angular 2

Having an issue with the beacon Minor propriety in a new function. The editor keeps saying that the name cannot be found, and I'm not sure how to resolve it. Function Example: listenToBeaconEvents() { this.events.subscribe('didRangeBeacons ...

NavigatedRoute and Auth-protect - problem retrieving ID from paramMap

Currently working on a website for my exam project, but encountering an issue with the AuthGuard not returning the correct ID in my code. event-details.component.ts getEvent(): void { const id = +this.route.snapshot.paramMap.get('id'); ...

Tips for utilizing PNG images in Next.js beyond the conventional PUBLIC folder

I have been trying to use images from a directory other than the Public folder by implementing the Next-Images library. Despite following the setup instructions in the documentation and watching various tutorials online, I am unable to load anything other ...

Guide for adjusting icon dimensions in Material-UI breakpoints

import { Container } from "@mui/material"; import * as React from "react"; import { Home } from "@mui/icons-material"; import PersonIcon from "@mui/icons-material/Person"; import FormatListBulletedIcon from "@mu ...

Tips for implementing a feature in Angular 6 that enables an input box to accept both negative and positive values within the range of 0 to

HTML markup <input type="number" min="0" max="100" required placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl"> Implementing TypeScript validation this.rateControl = new FormControl("", [Validators.max(100) ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Tips for efficiently finding and comparing text within the results generated by a for loop in Angular/Javascript

In my XML data, I have extracted all the tag names using a for loop and some other logic. Now, I am looking to find the word 'author' from the output values that are displayed in the console during the loop. If any of the output values match &apo ...

Tips for adjusting the dimensions of a map within the app.component.html

Within the code snippet below, my aim is to adjust the width and height of the map using the style tag shown here: <style> #map3 .map { width: 100%; height:90px; } </style> Despite trying various values for width an ...

Share a callback function with child components via props

My child container defines Ownprops like this: export interface OwnProps { prop1: string; prop2: "callback function" } I want to pass a callback function from the parent to this child in order to trigger a parent function from the child. However ...

Using TypeScript to deserialize various types from a shared object

I am currently dealing with a JSON array containing serialized objects, each of which has a type field. My challenge lies in deserializing them properly due to TypeScript not cooperating as expected: Check out the TypeScript playground for reference. type ...

Navigating through a multidimensional array in Angular 2 / TypeScript, moving both upwards and downwards

[ {id: 1, name: "test 1", children: [ {id: 2, name: "test 1-sub", children: []} ] }] Imagine a scenario where you have a JSON array structured like the example above, with each element potenti ...

Tips for running batch files prior to debugging in VS Code

Currently, I am working on a project using Typescript, nodeJS, and VS Code. When it comes to debugging in VS Code, I have set up configurations in my launch.json file. { "type": "node", "request": "launch", "name": "La ...

What is the reason behind the lack of exported interfaces in the redux-form typings?

I've been exploring how to create custom input fields for redux-form. My journey began by examining the Material UI example found in the documentation here. const renderTextField = ({input, label, meta: { touched, error }, ...custom }) => < ...

Exploring the wonders of using the Async Pipe with Reactive Extensions

I'm facing a little issue with the async pipe in Angular. Here's my scenario: I need to execute nested observables using the async pipe in HTML because I'm utilizing the on-push change detection strategy and would like to avoid workarounds ...

Exploring how React dynamically alters class names within snapshots

I am encountering issues with my React JS test cases as the snapshots keep failing on different systems. The problem lies in the generation of random classnames and row-index values. - Snapshot + Received @@ -6,11 +6,11 @@ <div class="MuiG ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

What is the proper method for integrating a loader into an observable HTTP request?

I need to implement a "loading" variable for my login method: Here is the current login method: public login(authDetails:any):any{ return this.http.post<any>('https://myapi.com/session', authDetails).pipe( map(response => { ...