简体   繁体   中英

karmajs fails to launch when node-openid-client is imported in typescript specification file

I am using node-openid-client to perform OpenIDConnect based authentication with an OpenID Provider.

I have now run into issues when I attempt to write test cases for this program. When the application is run from node CLI it functionally works. ie it gets the code and I can use it to get token as well !

The error that I am running into 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 ...

Above this error following are the activities Karma runner is performing -

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 are the logs generated by Karma when run with LOG_DEBUG configuration.

I am not using Angular or any other UI frameworks .

I have few questions based on these errors -

Q1 : I wonder why does karma parse the js file in node_modules folder? I am excluding it in tsconfig.json.

Based on the activities performed before the error, I notice that it is failing to bundle the required files of openid-client library. However, if I run browserify bundle for this library it succeeds. I guess I have done some configuration wrong in any of the file listed below.

Q2 : Please help me with how to determine which configuration property is at fault ! , or a solution itself will be much appreciated as well !

Q3 : Worrying question for me - Is openid-client not comptabile with karma test runner? Is such a limitation possible? I did not see any corresponding issue in GitHub repository.

Following are the files of interest which I kept editing to get around this error. However, I think I have hit a wall now.

In order to focus on the issue and see in black and white whether the openid-client is causing the issue, I had introduced a minimal test case targeting jasmine framework. The spec looks like this -

probe.spec.ts file

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

Now while experimenting I had removed the import in first line. If that is done; karma launches and reports the test case has been successful !

Dependencies (including dev) for 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 looks like this -

{
  "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 looks like this -

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

It seems I have figured out (with medium confidence levels) responses to my questions. Request the community to vote if this is plausible enough answer.

TL;DR - karma-typescript has a known limitation which is causing the error. Even without the karma-typescript plugin; node-openid-client as well is not expected to work in browser as-of now (2-October-2019T16:30UT). So, yes I cannot use node-opened-client with karma (which cannot work without browser even as-of now (2-October-2019T16:30UT) ). Viable alternate is to use mocha instead of karma.

Details for the aforesaid conclusion

File error.js region around line 24,2 looks like this


    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:    );

Line 24,2 corresponds to the closing braces of Object.assign call. If you notice there is an extra comma the line above. I removed it to see the error goes away. May it is a transpiler used by the library node-opened-client at fault. After fixing it I got following error


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

    ... keystore(reload = false) {
        assertIssuerConfigu ...

File issuer.js region around line 72 looks like this


    Line 68    /**
    Line 69    * @name keystore
    Line 70    * @api public
    Line 71    */
    Line 72    async keystore(reload=false) {
    Line 73        assertIssuerConfiguration(this, 'jkws_uri');

Line 72 uses the async keyword and the immediate question is whether async keyword is supported in the (com/trans)pilation process?

To test this hypothesis I removed the async keyword and noticed error location moved to the next occurrence of async.

I could not find much of fault in the node-openid-client library. But in karma-typescript plugin while the files are being bundled there is something going wrong terribly. Search in their repository yields few hints. In which i got cognizant of the configuration which could have caused the problem.

File configuration.ts region around Line 113 looks like this -

    ...
    Line 111    const defaultBundlerOptions: BundlerOptions = {
    Line 112        acornOptions: {
    Line 113            ecmaVersion : 7,
    Line 114            sourceType : "module"
    Line 115        },
    ...

If I change this version of ecmaVersion 7 right here in the local copy present in the node_modules folder, I got the issue resolved but I got stuck in another error but this time with spread syntax for arrays.

With focused search I landed on the SO question karma-typescript: import JS file with Async keyword . Apparently this is an open issue with karma-typescript which is yet in open state (2-October-2019T16:30UT). Instead of changing the js file you could set a undocumented property of karma-typescript. However, that does not get me closer to solution I had wished for !

Responding to the individual questions

Q1: I wonder why does karma parse the js file in node_modules folder? I am excluding it in tsconfig.json.

A1 : karma is bundling the dependent files for the test script to run in a browser . In this process the setting referred to in tsconfig.json is of no relevance.

Q2: Please help me with how to determine which configuration property is at fault !

A2 : For the error quoted in this SO question it is the karmaTypescriptConfig.bundlerOptions.acorOptions which accepts a JSON and one could set it in karma.conf.js as

    karmaTypescriptConfig: {
        bundlerOptions: {
            acornOptions: {
            ecmaVersion: 8,
        },
        transforms: [require("karma-typescript-es6-transform")()]
    }

Q3: Worrying question for me - Is openid-client not comptabile with karma test runner? Is such a limitation possible? I did not see any corresponding issue in GitHub repository.

A3 : Implicitly yes ! - openid-client is not compatible with karma because it uses browser and node-openid-client is not supported for such environments even if I overcome the challenge with karma-typescript by commenting it I will not be able to use it with karma which uses browser based test running.

Alternatively I could use mocha as test runner framework instead of karma. I checked; node-openid-client library themselves use mocha for testing. Mocha is first class citizen to nodejs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM