An issue arises with launching karma.js when importing node-openid-client in a TypeScript specification file

Utilizing the node-openid-client library for OpenIDConnect based authentication with an OpenID Provider.

Encountering challenges while attempting to write test cases for the program. The application runs smoothly from node CLI, obtaining the code and tokens successfully!

The specific error encountered is:

ERROR [source-reader.karma-typescript]: Error parsing code: Unexpected token (24:2)
in C:\VSCode\Projects\openid-client-test\javascript\node_modules\openid-client\lib\errors.js 
at line 24, column 2:

... );
if (response) {
     Object.defineProperty(th ...

Following this error, Karma runner performs the following activities:

INFO [compiler.karma-typescript]: Compiled 1 files in 3029 ms.

DEBUG [bundler.karma-typescript]: Project has 2 import/require statements, code will be bundled

DEBUG [es6-transform.karma-typescript]: Transforming C:\VSCode\Projects\openid-client-test\javascript\node_modules\openid-client\lib\index.js

These logs are generated by Karma when executed with LOG_DEBUG configuration.

No utilization of Angular or any other UI frameworks.

Queries arising from these errors:

Q1: Curious as to why Karma parses the js file in the node_modules folder despite being excluded in tsconfig.json.

Observing the failure to bundle required files of the openid-client library prior to the error. Browserify bundle for the library succeeds, suggesting incorrect configuration in the listed files below.

Q2: Seeking assistance in identifying the misconfigured property causing such conflicts! Solution suggestions are greatly welcomed.

Q3: Concerned whether openid-client is incompatible with the karma test runner? Can such a limitation exist? No related issues found in GitHub repository.

Files modified inclusively to troubleshoot the error. These efforts led to introducing a minimal jasmine-targeted test case. Specified as follows:

probe.spec.ts file

import { Issuer } from 'openid-client';
describe('Hello', () => {
  it('Checks', () => {
    expect('hello').toBe('hello');
  })
});

An experiment involved removing the first-line import. Resulting in successful execution reported by Karma!

Dependencies (including dev) specified in the package.json file

"dependencies": {
  "@types/node": "^12.7.5",
  "amazon-cognito-auth-js": "^1.3.2",
  "atob": "^2.1.2",
  "openid-client": "^3.7.2",
  "typescript": "^3.6.3",
  "xmlhttprequest": "^1.8.0"
},
"devDependencies": {
  "@types/jasmine": "^3.4.1",
  "jasmine-core": "^3.5.0",
  "karma": "^4.3.0",
  "karma-chrome-launcher": "^3.1.0",
  "karma-coverage-istanbul-reporter": "^2.1.0",
  "karma-jasmine": "^2.0.1",
  "karma-jasmine-html-reporter": "^1.4.2",
  "karma-spec-reporter": "0.0.32",
  "karma-typescript": "^4.1.1",
  "karma-typescript-es6-transform": "^4.1.1"
}

tsconfig.json detailing:

{
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compilerOptions": {
  "module": "commonjs",
  "target": "es2016",
  "noImplicitAny": false,
  "strictNullChecks": true,
  "moduleResolution": "node",
  "sourceMap": true,
  "importHelpers": true,
  "outDir": "output",
  "baseUrl": ".",
  "typeRoots": [
    "node_modules/@types"
  ],
  "types": [
    "@types/jasmine",
    "@types/node"
  ],
  "lib": [
    "es2017",
    "dom",
    "es2015.generator",
    "es2015.iterable",
    "es2015.promise",
    "es2015.symbol",
    "es2015.symbol.wellknown",
    "esnext.asynciterable"
  ]}
}

karma.conf.js structure provided:

module.exports = (config) => {
  config.set({
    frameworks: ['jasmine', 'karma-typescript'],
    plugins: [
      'karma-jasmine',
      'karma-typescript',
      'karma-chrome-launcher',
      'karma-spec-reporter',
      'karma-typescript-es6-transform'
    ],
    karmaTypescriptConfig: {
      tsconfig: "./tsconfig.json",
      compilerOptions: {
        allowJs: true
      },
      bundlerOptions: {
        entrypoints: /\.spec\.(ts|tsx)$/,
        addNodeGlobals: true,
        transforms: [require("karma-typescript-es6-transform")()]
      }
    },
    files: [{ pattern: 'src/**/*.+(js|ts)' }],
    preprocessors: {
      'src/**/*.+(js|ts)': ['karma-typescript']
    },
    client: {
      clearContext: false
    },
    reporters: ['spec', 'karma-typescript'],
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: true
  })
}

Answer №1

After conducting thorough research and analysis, I have come to a conclusion regarding the responses to my inquiries with a moderate level of confidence. I humbly request the community to vote on whether this answer is deemed plausible.

In summary - The issue that is causing the error is a known limitation within karma-typescript as outlined in this thread. Additionally, it has been determined that even without the karma-typescript plugin, node-openid-client is currently not expected to function properly in a browser environment as of October 2nd, 2019 (16:30 UT). Hence, the utilization of node-opened-client with karma is not feasible due to its dependency on a browser, as succinctly explained here and here (as of October 2nd, 2019 at 16:30 UT). A viable solution recommended by fellow users is to opt for mocha instead of karma.

Analyzing the provided evidence

The file error.js, particularly around line 24.2, exhibits an anomaly in the code structure:


    Line 16:    Object.assign(
    Line 17:        this,
    Line 18:        {error},
    Line 19:        (error_description && {error_description}),
    Line 20:        (error_uri && {error_uri}),
    Line 21:        (state && {state}),
    Line 22:        (scope && {scope}),
    Line 23:        (session_state && {session_state}),
    Line 24:    );

Upon closer inspection, it was observed that there was an extra comma present on the line above line 24.2. Upon rectifying this discrepancy, a new error surfaced during the transpilation phase.

...

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 implementation of TypeScript 3.5 resulted in a malfunction where the imported namespace was unable to locate the Enum during runtime

I recently upgraded an older Angular.js application from Typescript 2.7 to 3.5 and successfully compiled it using tsc.exe. During application runtime, I encountered an error message in certain parts of the code: TypeError: Cannot read property 'Enu ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

An item whose value is determined by the specific type of key it possesses

Consider the following scenario: enum MouseType { GENERAL_USE = 1, SPECIALIZED_USE = 2, } enum KeyboardType { GENERAL_USE = 3, SPECIALIZED_USE = 4, } interface MouseSpecifications { buttons: number; dpi: number; } interface KeyboardSpecifica ...

Refresh the mapbox source features in real-time

Currently, I am mapping out orders on a map with layers and symbols that have different statuses. When the status of an order changes, I want to update the color of the symbol accordingly. The layer configuration looks like this: map.addLayer({ id: &q ...

Exploring a different approach to utilizing Ant Design Table Columns and ColumnGroups

As per the demo on how Ant Design groups columns, tables from Ant Design are typically set up using the following structure, assuming that you have correctly predefined your columns and data: <Table columns={columns} dataSource={data} // .. ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...

How is it possible for this for loop to function properly without the need to pass the incrementing variable

I managed to compile my code and it's working fine, but there's something interesting - the variable that should reference the incrementing value is not included as an argument in the for loop. var _loop2 = function _loop2() { var p = docume ...

What causes the difference in inference for unspecified generics between a simple function call and a null-coalescing operator in TypeScript?

What causes the different types of a and b in the given code snippet? function empty<T>() { return [] as T[] } const defEmpty = empty() function test1(abc: number[]|null) { const a = abc ?? defEmpty const b = abc ?? empty() } Upon testing on t ...

The compiler is unable to locate the node_module (Error: "Module name not found")

Error: src/app/app.component.ts:4:12 - error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try npm i @types/node and then add node to the types field in your tsconfig. 4 moduleId: module.id, When att ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Adding a value to an array in TypeScript

When trying to add values to an array in my code, I encountered an error stating that "number" is not a valid type for the array. someArray: Array <{ m: number, d: Date}> = []; this.someArray.push(500,new Date(2020,1,15)); ...

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 }) => ...

Is it possible to utilize the $ symbol within the ngOnInit or constructor functions?

I recently encountered an issue while trying to use the dollar sign ($) in my constructor function, specifically within ngOnInit() and translate.instant. Here is a snippet of the code that caused the problem: declare var $: any; { var SelectedDevice = ...

Stop the print dialog box from appearing when using the Ctrl + P shortcut

I'm working on an Angular app and I want to prevent the print dialog from opening when pressing "Ctrl + P". To address this issue, I have implemented the following code: window.onbeforeprint = (event) => { event.stopPropagation(); cons ...

What is the best way to include an item in a list with a specific identifier using the useState Record data type in a React application built with TypeScript?

Here is the structure of my Record type: const PEOPLE_MAP_INIT: Record<string, Person[]> = { "1": [], "2": [], "3": [] }; I have initialized the useState like this: const [PEOPLE_MAP, SET_PEO ...

Using TypeScript, you can pass an object property name as a function argument while ensuring the type is

How can I define a type in a function argument that corresponds to one of the object properties with the same type? For instance, if I have an object: type Article = { name: string; quantity: number; priceNet: number; priceGross: number; }; and I ...

Tips for handling user click events in Angular 2?

In Angular2, I am facing an issue with two components. When a user clicks a button in component1, a method is triggered that stores data in the shared service to a variable. However, component2's ngOnInit() method initializes this variable to undefine ...

Creating dynamic form groups in Angular 4

I am currently working on a dynamic form group and I am facing a particular challenge. https://i.sstatic.net/m20IO.png Whenever I click on "add more," it should add 2 dynamic fields. Here is the function I am using: onAddSurgeries(){ const control = ...

Generate diagnostic logs in Visual Studio Code without using a language server

I have a straightforward extension for Visual Studio Code where I am looking to add warnings without the need to create a whole new language server. Is there a way to achieve this on the document or editor objects directly? My attempts at inspecting the ...