Typescript Jest testing reveals inaccurate error line information

While running a sample Jest test on a particular structure, I noticed that the errors in the output summary from Jest are not lining up correctly.

Here is a snippet from my package.json file:

"devDependencies": {
    "@types/jest": "^22.0.1",
    "jest": "^22.1.4",
    "jest-preset-angular": "^5.0.0",
    "ts-jest": "^22.0.1",
    "typescript": "^2.6.2"
},

The specific issue can be seen in the output below:

Venue › Venue Structure › should have all the structure fields

expect(received).toBeDefined()

Expected value to be defined, instead received
  undefined

  20 |              it('should be an instance of DataStructure', () => {
  21 |                      expect(VenueInfo instanceof DataStructure).toBeTruthy();
> 22 |              })
  23 |
  24 |              it('should have the proper number of data fields', () => {
  25 |                      expect(VenueInfo.NumberOfFields).toBe(14);              // LastUpdated is added automatically

  at src/structures/Venue.spec.ts:22:35

Interestingly, the error seems to be occurring at line 29 according to the information within the it() function.

The relevant part of the Venue.spec.ts file is provided below:

import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';

import { Venue } from './Venue';
import { DataStructure } from '../library/base/DataStructure';

describe('Venue', () => {
    let VenueInfo: Venue;

    beforeEach(() => {
        VenueInfo = new Venue();
    });

    describe('Class', () => {

        it('should be an instance of Venue', () => {
            expect(VenueInfo instanceof Venue).toBeTruthy();    ;
        });

        it('should be an instance of DataStructure', () => {
            expect(VenueInfo instanceof DataStructure).toBeTruthy();
        })

        it('should have the proper number of data fields', () => {
            expect(VenueInfo.NumberOfFields).toBe(14);          });
    });

    describe('Venue Structure', () => {
        it('should have all the structure fields', () => {
            expect(VenueInfo.Key).toBeDefined();
            expect(VenueInfo.Description).toBeDefined();
            expect(VenueInfo.Address1).toBeDefined();
            expect(VenueInfo.Address2).toBeDefined();
            expect(VenueInfo.City).toBeDefined();
            expect(VenueInfo.Province).toBeDefined();
            expect(VenueInfo.Country).toBeDefined();
            expect(VenueInfo.PostalCode).toBeDefined();
            expect(VenueInfo.Telephone).toBeDefined();
            expect(VenueInfo.Latitude).toBeDefined();
            expect(VenueInfo.Longitude).toBeDefined();
            expect(VenueInfo.MajorIntersection).toBeDefined();
            expect(VenueInfo.DartBoards).toBeDefined();
        });
    });
});

Another important file to consider is tsconfig.json:

{
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
            "dom",
            "es2015"
        ],
        "module": "es2015",
        "moduleResolution": "node",
        "sourceMaps": true,
        "target": "es5"
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules",
        "src/**/*.spec.ts",
        "src/test-config"
    ],
    "compileOnSave": false,
    "atom": {
        "rewriteTsconfig": false
    }
}

Lastly, there was also a tsconfig.spec.json file present in the src directory of my Ionic application, here is what it contained:

{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "allowJs": true,
        "module": "commonjs",
        "outDir": "../out-tsc/spec",
        "sourceMaps": true,
        "target": "es5"
    },
    "files": [
        "**/*.ts"
    ],
    "include": [
        "*.spec.ts",
        "**/*.spec.ts",
        "**/*.d.ts",
        "test-config/*.ts",
        "test-config/**/*.ts"
    ]
}

Answer №1

Typescript Jest test displaying incorrect error lines

Verify that your tsconfig.json includes the setting sourceMap: true

Answer №2

Building on the suggestion from @Juan Carlos, I found that modifying the babel configuration instead of the compiler options was more effective for me. I achieved this by including the following code in the jest config file:

  "globals": {
    "ts-jest": {
      "babelConfig": {
        "sourceMaps": true
      }
    }
  }

Here is a helpful resource on configuring babel in your jest file.

Answer №3

My code is exhibiting discrepancies of several lines, with the issue becoming more pronounced as you navigate further down the file. I have provided a detailed explanation of this problem in my post (Jest 26 & React - Line Number Errors). Additionally, I have set up a minimal test repository for anyone willing to lend a hand.

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 method for utilizing a class variable without assigning a value to it initially

class testClass { student: { name: string, age: number } constructor(options?: any) { this.student = { name: '', age: 0 }; } setStudent(name:string, age:number) { this.student.name ...

When implementing JSS with React and TypeScript, certain CSS properties may encounter a `type is unassignable` error

Recently delving into TypeScript, I've encountered an issue within my project that was created using create-react-app with TypeScript and incorporates JSS. It appears that certain CSS properties are causing errors. Specifically, the pointerEvents and ...

Leverage context to facilitate communication between components operating at various levels of the system

I am currently working on the settings pages of my applications. Each page features a common SettingsLayout (parent component) that is displayed across all settings pages. One unique aspect of this layout is the presence of an ActionsBar, where the submit/ ...

Tips for Resolving TypeScript Error 7053 when using the handleChange function in a React Form

Seeking assistance with creating a versatile handleChange function for a React form. The goal is for the handleChange function to update the state value whenever a form field is modified, while also accommodating nested values. Below is my attempt: const ...

AngularTS regex that enforces the use of a decimal point in numbers

I am working on a requirement where the input should only accept decimal characters, negative or positive. I need to use regex to make the decimal point mandatory, however it is currently allowing negative whole numbers which is not the desired behavior. I ...

Angular: sending the user input to the component

I'm trying to link the value of an HTML input field to a variable 'numToAdd' in my component, and then increment the 'numToAdd' variable by 1. However, I'm facing difficulties passing the input value to the component variable. ...

What is the best way to properly configure axios testing in a React application?

Struggling with testing axios in React - any help? This is my current test.js file attempt: jest.mock('axios'); describe('RssFeed', () => { let component; let data; beforeEach( () => { data = data { data: {...} ...

A guide on leveraging typeof within function parameters to ensure accurate variances

Let's create a simple class hierarchy and a list of instances. The goal is to filter items from the list of instances based on their class. There are a couple of challenges: We cannot use the typeof T syntax. How can this be written? We cannot decla ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Issue: Unable to locate the name 'ContactField' in Ionic 2

While attempting to use Ionic2 to save a contact, an error occurs when running the app through the command line. The cordova-plugin-contacts has been properly installed. Below is the code snippet: import { Component } from '@angular/core'; impo ...

Creating a higher order component (HOC) that utilizes both withRouter and connect functions in React

I am currently working with the following stack: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87f5e2e6e4f3c7b6b1a9b6b4a9b6">[email protected]</a> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

How to Implement Animations with Angular 2 Directives

Incorporating a special Directive onto elements to monitor their current scroll position seems like a handy feature. Here's an example: @Directive({ selector: '[my-scroll-animation]' }) My goal is to make the element appear on screen ...

What is the best way to sort an array based on a person's name?

I have a list of different groups and their members: [ { "label": "Group A", "fields": [ { "value": "color1", "name": "Mike" }, { &quo ...

The connection named "Default" could not be located for use with TypeOrm and Express

I am currently facing an issue with my setup involving TypeORM. It seems that Express is being initialized before the connection to the database is established with TypeORM, causing an error message "Connection default not found." Here is a snippet of the ...

Decoding enum interface attribute from response object in Angular 4 using typescript

From an API response, I am receiving an enum value represented as a string. This enum value is part of a typescript interface. Issue: Upon receiving the response, the TypeScript interface stores the value as a string, making it unusable directly as an en ...

What is the method for deducing the return type based on the parameter type in a generic function?

Check out this code snippet featuring conditional types: class X { public x: number; } class Y { public y: number; } type DataCategory = "x" | "y"; type TData<T extends DataCategory> = T extends "x" ? X : T extends "y" ? Y : ne ...

What are the steps to achieve full screen mode in Google Chrome within an Angular 4 Application?

I'm working on an application and I'm looking to incorporate a feature where, when a user navigates from one component to another, the new component's ngOnInit method triggers the Chrome browser to enter full screen mode, similar to pressing ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

Convert a TypeScript array of strings to a boolean array: a step-by-step guide

Upon receiving a list of objects from the front end as: item=["false","true"] I proceed to check a column within my records to identify values containing "true" or "false" using the following code: this.records.filter(x=> items.includes(x.column)) Unf ...

Tips for simulating changing data in snapshot tests?

Two challenge are puzzling me currently: The snapshot test for a router page includes custom routers with guards specifically for logged in users. Each time I run this test, a different generated key is produced. I am using new Date() in a date pick ...