Angular项目:Chrome调试器无法正确进行单元测试

问题描述

在Angular 8应用中,调试单元测试时,Chrome调试器出现问题。 调试单元测试代码本身是可行的,直到我要逐步浏览生产代码(由测试调用)为止。

我使用ng test启动测试。在Chrome浏览器中,我在单元测试代码添加一个断点,并且单步执行代码会在调试器中显示正确的行。但是,当我进入生产代码时,它会跳到错误的行。有时它会跳到空行和声明,这根本没有意义。大概是,源地图没有正确生成,但是我不确定。

如何使单元测试调试起作用?我试图将目标从 es5 设置为 es2015 ,但是之后我无法再在Chrome中打开源文件

tsconfig.spec.json

{
    "extends": "../tsconfig.json","compilerOptions": {
        "outDir": "../out-tsc/spec"
    },"files": ["test.ts","polyfills.ts"],"include": ["**/*.spec.ts","**/*.d.ts","../node_modules/@mycompany/**/*.ts"],"exclude": ["../node_modules/@mycompany/**/*.spec.ts"]
}

tsconfig.json

{
    "extends": "./node_modules/gts/tsconfig-google.json","compileOnSave": false,"compilerOptions": {
        "outDir": "./dist/out-tsc","sourceMap": true,"declaration": false,"moduleResolution": "node","emitDecoratorMetadata": true,"experimentalDecorators": true,"noUnusedLocals": true,"noUnusedParameters": true,"strict": false,"target": "es5","typeRoots": ["node_modules/@types"],"types": [
            "node","jasmine","googlemaps"
        ],"lib": [
            "es2017","dom"
        ],"baseUrl": ".","paths": {
            "app/*": ["src/app/*"],"assets/*": ["src/assets/*"],"shared/*": ["src/app/shared/*"]
        }
    }
}

angular.json

.......
                "test": {
                    "builder": "@angular-devkit/build-angular:karma","options": {
                        "main": "src/test.ts","karmaConfig": "./karma.conf.js","polyfills": "src/polyfills.ts","tsConfig": "src/tsconfig.spec.json","scripts": [],"stylePreprocessorOptions": {
                            "includePaths": ["src/css","node_modules/@mycompany/styles/lib/sass"]
                        },"styles": ["src/css/styles.scss"],"assets": [
                            "src/assets","src/favicon.ico",{
                                "glob": "**/*","input": "node_modules/@mycompany/styles/lib/images","output": "/assets/images"
                            }
                        ]
                    }
                },.......

解决方法

问题出在我的 package.json 中。我使用了一个npm run test命令来调试单元测试并生成其代码覆盖率。但是似乎--code-coverage标志会干扰源地图。

因此,我创建了第二个命令来覆盖代码。两者现在都具有魅力!如果我运行npm test并使用Chrome添加断点,则可以单步执行代码!

初始配置不起作用

"scripts": {
        "ng": "ng",....
        "test": "ng test --code-coverage",....
}

工作配置

"scripts": {
        "ng": "ng",....
        "test": "ng test",// <- default task,no coverage such that source maps will work!
        "test:coverage": "ng test --code-coverage",....
}