Unit testing Jest for TypeScript files within a module or namespace

Recently, I've joined a mvc.net project that utilizes typescript on the frontend. There are numerous typescript files wrapped within module Foo {...}, with Foo representing the primary module or namespace.

All these typescript files are transpiled into a single file named Foo.js. The challenge lies in the fact that none of the typescript files have export module Foo{...} to export the namespace. As I aim to write unit tests for this setup, I've opted for the Jest framework.

The question now is how can I import objects from my typescript files into my test?

In my package.json file:

{
  "version": "1.0.0",
  "name": "Foo-Web",
  "private": true,
  "devDependencies": {
    "@types/bootstrap": "4.1.2",
    "@types/jquery": "^3.3.16",
    ... and a variety of other libraries
  },
  "scripts": {
    "test": "jest"
  }
}

In my tsconfig.json file:

{
  "compileOnSave": true,
  "compilerOptions": {
    "isolatedModules": false,
    "allowSyntheticDefaultImports": true,
    "jsx": "react",
    "lib": [
      "dom",
      "es2017"
    ],
    "noImplicitAny": false,
    "noEmitOnError": true,
    "outFile": "Out/dist/Foo.js",
    "removeComments": true,
    "sourceMap": true,
    "target": "es5"
  },
  "exclude": [
    "**/bower_components/*",
    "**/node_modules/*",
    "**/dist/*"
  ],
}

My jest.config.js file looks like:

module.exports = {
    "testMatch": [
        "**/__tests__/**/*.+(ts|tsx|js)",
        "**/?(*.)+(spec|test).+(ts|tsx|js)"
    ],
    "transform": {
        "^.+\\.(ts|tsx)$": "ts-jest"
    },
    "moduleFileExtensions": ['js', 'jsx', 'ts', 'tsx']
}

The format of my typescript files typically follows:

module Foo {
    interface blablabla ....

    export class hahaha{
     ... class implementation
    }
}

An example test file snippet:

...
var ct = new Foo.SomeClass(testProp)
....

When running the jest test, I encounter the error:

Foo is not defined

Answer №1

Everything is working fine on my end. By the way:

Instead of using the deprecated internal 'module' syntax, consider using the 'namespace' keyword.

index.ts:

export module Foo {
  export class SomeClass {
    constructor(private prop) {}
  }
}

index.test.ts:

import { Foo } from './';

describe('63957901', () => {
  it('should succeed', () => {
    const testProp = {};
    const ct = new Foo.SomeClass(testProp);
    expect(ct).toBeInstanceOf(Foo.SomeClass);
  });
});

Result of unit testing:

 PASS  src/stackoverflow/63957901/index.test.ts (10.923s)
  63957901
    ✓ should pass (4ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.401s

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

Utilizing ngx-logger Dependency in Angular 6 for Efficient Unit Testing

Have you ever attempted to test classes in Angular that rely on ngx-logger as a dependency? I am looking for guidance or examples of how this can be achieved using testing frameworks such as Jasmine. It seems there are limited resources available on mock ...

What is the best way to output a JSX element using an inline switch statement?

I have been attempting to use an inline switch in order to return an element, but all I am getting is an empty <span> </span>. What could be the issue here? getRowTdForHeader: (header: string, entry: response) => { return (< ...

What is the most effective way to perform unit testing on the "present" function of an Ionic alert controller?

I decided to write a unit test for the alert present function that gets triggered after creating an alert. This is what my code looks like. it('should call attempt To call alert present', async () => { const alert = { header: 'P ...

The exclude option in Nest JS middleware does not prevent the middleware from running on excluded routes

I'm having an issue with excluding certain routes from the middleware. The .exclude option doesn't seem to be working as expected, as the middleware is still being applied to the excluded routes. Here is the code for the Middleware: https://i.st ...

Create a .d.ts file for a custom JavaScript file

I am working on an application written in JavaScript and considering incorporating TypeScript for a new feature. Currently, I have a base class defined in JavaScript as shown below: // base.js module.exports = function BaseClass () { // ... ... }; M ...

Encountering TS2344 error when referring to the Component Ref in Vue.js during typing operations

I received a component reference on my FormCheckbox component from a patternlib. When I tried to incorporate the component into my own TestComp component, I encountered this TypeScript error that left me puzzled: TS2344: Type '{ name: string; mixins: ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

The folder creation in the 'outDir' directory by TSC continues to grow

Hello! Currently, I am engaged in a small TypeScript project where I need to utilize two separate tsconfig.json files, both of which inherit from my main tsconfig.base.json file. Unfortunately, I encountered an issue with the compiler creating unnecessar ...

Steps for styling the header of an Antd Collapse Panel

I'm attempting to modify the text color in the header of an ant panel. Below is the entire ant collapse component code: <Collapse accordion defaultActiveKey={defaultOpenPanel}> <StyledCollapsePanel key="tasksAssignedToMe" header={ ...

What is the best way to set up initial state in react-native-day-picker?

I have been experimenting with implementing react-native-calendar into my project. Here is the code snippet I am working on: import React from 'react'; import {Calendar} from 'react-native-day-picker'; const MyCalendar = () => { ...

What is the process for extracting the paths of component files from an Angular ngModule file?

I've been on the lookout for automation options to streamline the process of refactoring an Angular application, as doing it manually can be quite tedious. We're working on reducing our app's shared module by extracting components/directive ...

Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below: const myRoutes: Routes = [ {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]}, {path: 'FirstComponent ', component: FirstCompon ...

Manage thrown errors using http.post().subscribe()

There is a backend API for logging in with the possibility of returning a 401 Unauthorized error if the password provided is incorrect. I am wondering how to effectively manage and handle exceptions raised in Angular when interacting with this API. this.h ...

An effective way to define the type of a string property in a React component using Typescript

One of the challenges I'm facing is related to a React component that acts as an abstraction for text fields. <TextField label="Enter your user name" dataSource={vm} propertyName="username" disabled={vm.isSaving} /> In this set ...

Jest is unable to execute tests containing methods within a .tsx file

Typically, I only test files ending with .ts, but this time I have a file containing utility methods that return a react element. Therefore, my file has a .tsx extension and includes components from material ui and other libraries. Initially, I encountere ...

Invoke a custom AWS CodeBuild project in CodePipeline using a variety of parameters

Imagine having a CodePipeline with 2 stages structured like this: new codepipeline.Pipeline(this, name + "Pipeline", { pipelineName: this.projectName + "-" + name, crossAccountKeys: false, stages: [{ stageName: &apos ...

The blank screen mystery: ionic and Google maps integration not playing nice

I've been struggling to integrate Google Maps into my web application. Unfortunately, all I see is a blank screen with no errors. Here's the current code snippet that I have. It seems like there might be an issue with the mapElement variable, but ...

What could be the reason for Jest flagging CSS as untested instead of identifying untested functions?

While working on my vue3 project and writing tests with jest, I have encountered an issue where jest is incorrectly marking the CSS within several single file components as untested, even though it doesn't need to be tested. Moreover, its assessment ...

Exported data in Vue3 components cannot be accessed inside the component itself

Essentially, I'm working on creating a dynamic array in Vue3. Each time a button is clicked, the length of the array should increase. Below is the code snippet. <div class="package-item" v-for="n in arraySize"></div> e ...

TypeScript seems to be failing to detect the necessary checks before they are used

I've been pondering on how to ensure TypeScript acknowledges that I am verifying the existence of my variables before using them. Below is the code snippet : Here's the function responsible for these checks: function verifyEnvVars(){ if (!proc ...