The code executes successfully, but encounters an error with 'instanceof' when being imported through the

In the process of writing a unit test using Mocha, I encountered some peculiar behavior. The test involves calling a static method of a Class that converts a LatLng to a leaflet L.LatLng object. At the end of the test, I validate whether the returned object is truly an instance of L.LatLng. To my surprise, the test failed despite it being an instance of L.LatLng. After spending several hours investigating, I was able to pinpoint the issue to the following problem.

When I import the Converter class using the tsconfig path parameter:

import { LeafletConverter } from '@maps/leaflet/leaflet-converter';

The test fails. However, if I import it using a relative path:

import { LeafletConverter } from '../../../app/maps/leaflet/leaflet-converter';

The test passes without any errors. So, the question arises - why does this happen and is there a way to maintain the '@maps/...' import style?

Versions:

$ tsc --version
Version 3.6.3

VSCode 1.39.2

Test file:

    import { expect } from 'chai';
    import 'mocha';
    import L from "leaflet";
    import { LeafletConverter as DirectLeafletConverter } from '../../../app/maps/leaflet/leaflet-converter';
    import { LeafletConverter } from '@maps/leaflet/leaflet-converter';
    import { LatLng } from '@maps/lat-lng';


    describe.only('maps/leaflet/asdf', () => {


        it('tsconfig path import - this test fails', () => {
            const leafletll = LeafletConverter.toLeafletLatLng(new LatLng(1,2));
            const test = leafletll instanceof L.LatLng;
            expect(test).to.be.true;
        });

        it('direct import - this test passes', () => {
            const leafletll = DirectLeafletConverter.toLeafletLatLng(new LatLng(1,2));
            const test = leafletll instanceof L.LatLng;
            expect(test).to.be.true;
        });


    });

LeafletConverter.ts

    import { LatLng } from "@maps/lat-lng";
    import L from "leaflet";
    import { LatLngBounds } from "@maps/lat-lng-bounds";

    export abstract class LeafletConverter {
        private constructor(){}

...


        public static toLeafletLatLng(latLng: LatLng): L.LatLng  {
            let result: L.LatLng = null;

            if(LatLng.isValid(latLng)) {
                result = L.latLng(latLng.lat,latLng.lng);
            }

            return result;
        }

...

    }

Test command & output:

$ "C:\\Program Files\\nodejs\\node.exe" --inspect-brk=22915 node_modules\\mocha\\bin\\_mocha -r ts-node/register -r tsconfig-paths/register --timeout 30000 --colors C:\\Users\\Asdf\\tmp\\rm.js\\group
test/**/*.test.ts
Debugger listening on ws://127.0.0.1:22915/e1b8ec38-90ac-41dd-aded-c2c20e2ffa28
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.


  maps/leaflet/asdf
    1) tsconfig path import
    √ direct import        


  1 passing (14ms)
  1 failing

  1) maps/leaflet/asdf
       tsconfig path import:

      AssertionError: expected false to be true
      + expected - actual

      -false
      +true

      at Context.<anonymous> (C:\Users\Asdf\tmp\rm.js\group-clusterer\src\test\maps\leaflet\asdf.test.ts:16:27)



Waiting for the debugger to disconnect...

package.json

{
  "name": "typescript-webpack-seed-project",
  "version": "0.0.1",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha -r ts-node/register -r tsconfig-paths/register src/test/**/*.test.ts",
    "compile": "npx tsc",
    "cc": "npx tsc -w",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/chai": "^4.2.3",
    "@types/googlemaps": "^3.38.0",
    "@types/leaflet": "^1.5.5",
    "@types/mocha": "^5.2.7",
    "@types/node": "^12.12.5",
    "@types/q": "^1.5.2",
    "@types/rbush": "^2.0.3",
    "chai": "^4.2.0",
    "jsdom": "15.2.1",
    "jsdom-global": "3.0.2",
    "leaflet": "^1.5.1",
    "mocha": "^6.2.1",
    "ts-loader": "^6.2.0",
    "ts-node": "^8.4.1",
    "tsconfig-paths": "^3.9.0",
    "tsconfig-paths-webpack-plugin": "^3.2.0",
    "tslint": "^5.20.0",
    "typescript": "^3.6.3",
    "uglifyjs-webpack-plugin": "^2.2.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9"
  },
  "dependencies": {
    "q": "^1.5.1",
    "rbush": "^3.0.1"
  }
}

Answer №1

Discovered the solution after identifying the root cause of the issue related to the absolute path to the ts files in the mocha command line command. Upon making this adjustment...

$ "C:\\Program Files\\nodejs\\node.exe" --inspect-brk=22915 node_modules\\mocha\\bin\\_mocha -r ts-node/register -r tsconfig-paths/register --timeout 30000 --colors C:\\Users\\Asdf\\tmp\\rm.js\\group-clusterer/src/test/**/*.test.ts

and changing it to this...

$ "C:\\Program Files\\nodejs\\node.exe" --inspect-brk=22915 node_modules\\mocha\\bin\\_mocha -r ts-node/register -r tsconfig-paths/register --timeout 30000 --colors src/test/**/*.test.ts

Everything started working smoothly. The reason behind this? Still a mystery to me...

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

Cannot assign an array of Typescript type Never[] to an array of objects

Creating an object array can sometimes lead to errors, let's take a look at an example: objectExample[a].push({ id: john, detail: true }); objectExample[a].push({ id: james, detail: false}); const objectExample = { a = [ { id: john, detail: true} ...

Dealing with a Typescript challenge of iterating over a tuple array to extract particular values

I am struggling with writing a function that extracts names from an array of tuples, where each tuple includes a name and an age. My current attempt looks like this: type someTuple = [string, number] function names(namesAndAges: someTuple[]) { let allNa ...

I am facing difficulties with importing components in React

Hey everyone, I wanted to share my App file with you: import React, { Component } from 'react'; import test2 from './test2'; import './App.css'; class App extends Component { render() { return <test2 />; } } ex ...

Is it possible for a primitive value to function as a type within Typescript?

Is it possible for a primitive value to be considered as a type in Typescript? For example, is the type below considered valid? If not, how can it be modified to make it valid? export type Status = { completed: false; } ...

Ionic: Automatically empty input field upon page rendering

I have an input field on my HTML page below: <ion-input type="text" (input)="getid($event.target.value)" autofocus="true" id="get_ticket_id"></ion-input> I would like this input field to be cleared eve ...

viewing state data using reactjs

In an attempt to incorporate react context into one of my projects, I'm facing a challenge. Specifically, I want to showcase the state information once the state is modified, i.e., when the confirmFavourites function is invoked. export class AppProvi ...

Make sure to always utilize an alias when setting up automatic imports

Is there a method to ensure that autoimport always utilizes the alias for importing modules in a project with VSCode? I want to consistently use the alias, even when it's a sibling component, without any exceptions. Instead of import { Navbar } from ...

"Encountering a Type Error when using Ramda's propOr function in

Struggling with a typing issue in Typescript while using Ramda. Here's my dilemma: My code const podName = R.propOr(null, 'podName', node) as String | null error: TS2352:Type 'propOr_general_011' cannot be converted to type &ap ...

I am attempting to update the URL of an iframe dynamically, but I am encountering an issue: the Error message stating that an Unsafe value is being

Currently, I am attempting to dynamically alter the src of an iframe using Angular 2. Here is what I have tried: HTML <iframe class="controls" width="580" height="780" src="{{controllerSrc}}" frameborder="0" allowfullscreen></iframe> COMPONE ...

Creating a customized HTTP class for Bootstrap in Angular 2 RC 5

During my experience with Angular 2 RC 4, I encountered a situation where I needed to create a class called HttpLoading that extended the original Http class of Angular2. I managed to integrate this successfully into my project using the following bootstr ...

Resolving typing complications with Typescript in React higher order components for utilizing an alias for components

Attempting to devise a Higher Order Component (HOC) that can also double as a decorator for the following purpose: Let's say there is a component named "counter" interface ICounterProps { count: number; } interface ICounter<T> extends React ...

How to use TypeScript to modify button styling with an OnClick() event handler

Learning TypeScript with Existing Code Transition Currently, I am delving into the world of TypeScript and in the process of converting my CoffeeScript code to TypeScript (specifically Lit Web Component). Confusion on Translation Process I'm encount ...

Is there a way to verify the presence of multiple array indices in React with TypeScript?

const checkInstruction = (index) => { if(inputData.info[index].instruction){ return ( <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ __html: replaceTextLinks(inputData.info[index].instruction) ...

Uploading to npm unsuccessful as the specified file in the `main` attribute was not successfully published

I am currently facing an issue while trying to publish a package on npm. The .js file I specified in the package.json is not being included with the package. My project is built using typescript, and I transpile it using the following npm script... "prepu ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

Error encountered when importing 'xx' from the path 'paths/xx.svg' using @svgr/webpack

@svgr/webpack import yy from 'paths/yy.svg' Error:unknown:Unexpected token, this is a fresh yarn create react-app xx --typescript project, import yySvg from 'paths/yy.svg'; SyntaxError: unknown: Unexpected token, expected "," (3:22) ...

What is the Best Method for Dividing an Array in Typescript?

I'm working on a project using Angular2, and I have a collection of parties. const PARTIES: Party[] = [ { id: 1, title: "Main Event", description: "The biggest, most extravagant event in the last 10,000,000 years." }, { id: 2, title: "Secondary E ...

Retrieve a list of all file names within a designated directory using Angular

I am working on my Angular app and I need to list all the file names inside the assets folder. To achieve this, I am planning to utilize the npm library called list-files-in-dir https://www.npmjs.com/package/list-files-in-dir Here is the service impleme ...

What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in makin ...

Unable to run the command npm run env:restart

Currently, I am in the process of running a basic example. The initial setup involved configuring the convector workspace by installing convector-cli and hurley, as well as performing an npm installation. However, when attempting to execute npm run env:r ...