После обновления с Angular 7 до Angular 8 мой тест канала прекратил работать: TypeError: undefined не повторяется - PullRequest
1 голос
/ 02 октября 2019

Я использую Jest для модульного тестирования моих компонентов Angular8. Я выполнил обновление с A7, где прошли испытания. Теперь я получаю сообщение об ошибке:

FAIL src/app/core/pipes/client/client.pipe.spec.ts (21.395s)
  ● ClientPipe › should format person

    TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

      10 | export class ClientPipe implements PipeTransform {
      11 |
    > 12 |   constructor(
         |               ^
      13 |     private readonly personPipe: PersonPipe,
      14 |     private readonly organizationPipe: OrganizationPipe) {}
      15 |

      at Object.<anonymous>.__read (src/app/core/pipes/client/client.pipe.ts:12:46)
      at Object.<anonymous>.__spread (src/app/core/pipes/client/client.pipe.ts:28:72)

Вот фрагмент кода:

@Pipe({
  name: 'client'
})
export class ClientPipe implements PipeTransform {

  constructor(
    private readonly personPipe: PersonPipe,
    private readonly organizationPipe: OrganizationPipe) {}

  transform(client: Client | any, args?: any): any {
    if (client.person) {
      return this.personPipe.transform(client.person, ...args);
    } else {
      return this.organizationPipe.transform(client.organization, ...args);
    }

    return ' — ';
  }

}

Ошибка на самом деле происходит из строки:

return this.personPipe.transform(client.person, ...args)

, где используется оператор spread . tsconfig.spec.json расширяет tsconfig.json, где target установлен на es5, поэтому я не понимаю, почему Jest должен потерпеть неудачу.

В браузере я получил похожую ошибку ( Ошибка:Найден не вызываемый @@ iterator ). Это помогло изменить tsconfig.json target с es2015 на es5. Но я беспомощен с конфигурацией Jest.

tsconfig.spec.ts:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "types": ["jest"]
  },
 "files": [
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "downlevelIteration": true,
    "module": "esnext",
    "outDir": "./dist/out-tsc",
    "baseUrl": "./src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "types": ["jest"],
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

package.json с Jest config:

{
  "name": "Test",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "serve": "node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng serve",
    "test": "jest",
    "test-ci": "jest",
    "lint": "ng lint",
    "lint-ci": "ng lint --format tslint-teamcity-reporter",
    "format:check": "prettier --config ./.prettierrc --list-different \"src/{app,environments,assets}/**/*{.ts,.js,.json,.css,.scss}\"",
    "e2e": "ng e2e",
    "test:debug": "node --inspect node_modules/jest/bin/jest --watch --runInBand -t 'ClientPipe'"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "8.2.6",
    "@angular/cdk": "8.2.0",
    "@angular/common": "8.2.6",
    "@angular/compiler": "8.2.6",
    "@angular/core": "8.2.6",
    "@angular/flex-layout": "8.0.0-beta.27",
    "@angular/forms": "8.2.6",
    "@angular/material": "8.2.0",
    "@angular/material-moment-adapter": "8.2.0",
    "@angular/platform-browser": "8.2.6",
    "@angular/platform-browser-dynamic": "8.2.6",
    "@angular/router": "8.2.6",
    "@ngrx/effects": "8.3.0",
    "@ngrx/router-store": "8.3.0",
    "@ngrx/store": "8.3.0",
    "@ngrx/store-devtools": "8.3.0",
    "@ngx-translate/core": "11.0.1",
    "@ngx-translate/http-loader": "4.0.0",
    "core-js": "3.2.1",
    "error-stack-parser": "2.0.3",
    "hammerjs": "2.0.8",
    "lodash": "4.17.15",
    "moment": "2.24.0",
    "ngx-take-until-destroy": "5.4.0",
    "rxjs": "6.5.3",
    "tslib": "^1.10.0",
    "ts-md5": "1.2.4",
    "web-animations-js": "2.3.2",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-builders/jest": "7.4.2",
    "@angular-devkit/build-angular": "0.803.6",
    "@angular/cli": "8.3.4",
    "@angular/compiler-cli": "8.2.6",
    "@angular/language-service": "8.2.6",
    "@ngrx/schematics": "8.3.0",
    "@types/jest": "23.3.14",
    "@types/lodash": "4.14.125",
    "@types/node": "8.10.36",
    "browser-sync": "2.26.7",
    "codelyzer": "5.1.2",
    "istanbul-reports": "2.2.5",
    "jest": "24.8.0",
    "jest-cli": "24.1.0",
    "jasmine-marbles": "0.4.1",
    "jest-preset-angular": "7.1.1",
    "jest-sonar-reporter": "2.0.0",
    "jest-teamcity-reporter": "0.9.0",
    "json-loader": "0.5.7",
    "ngx-wallaby-jest": "0.0.2",
    "prettier": "1.18.2",
    "protractor": "5.4.1",
    "rxjs-tslint-rules": "4.25.0",
    "ts-node": "7.0.1",
    "tslint": "5.16.0",
    "tslint-eslint-rules": "5.4.0",
    "tslint-microsoft-contrib": "6.1.1",
    "tslint-teamcity-reporter": "3.2.2",
    "typescript": "3.5.3",
    "wallaby-webpack": "3.9.15"
  },
  "jest": {
    "preset": "jest-preset-angular",
    "globals": {
      "ts-jest": {
        "tsConfig": "<rootDir>/src/tsconfig.spec.json",
        "stringifyContentPathRegex": "\\.html$",
        "astTransformers": [
          "jest-preset-angular/InlineHtmlStripStylesTransformer"
        ],
        "diagnostics": {
          "warnOnly": true
        }
      }
    },
    "moduleNameMapper": {
      "@core/(.*)": "<rootDir>/src/app/core/$1",
      "@shared/(.*)": "<rootDir>/src/app/shared/$1",
      "@views/(.*)": "<rootDir>/src/app/views/$1",
      "@app/(.*)": "<rootDir>/src/app/$1",
      "environments/(.*)": "<rootDir>/src/environments/$1"
    },
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupJest.ts"
    ],
    "testResultsProcessor": "jest-teamcity-reporter"
  }
}

Редактировать 1 - в консоли есть дополнительное предупреждение, которое может быть или не быть подсказкой

ts-jest[jest-transformer] (WARN) Got a `.js` file to compile while `allowJs` option is not set to `true` (file: C:\xxxx\node_modules\@ngrx\effects\bundles\effects.umd.js). To fix this:
- if you want TypeScript to process JS files, set `allowJs` to `true` in your TypeScript config (usually tsconfig.json)
- if you do not want TypeScript to process your `.js` files, in your Jest config change the `transform` key which value is `ts-jest`   so that it does not match `.js` files anymore
ts-jest[jest-transformer] (WARN) Got a `.js` file to compile while `allowJs` option is not set to `true` (file: C:\xxxx\node_modules\@ngrx\store\bundles\store.umd.js). To fix this:
- if you want TypeScript to process JS files, set `allowJs` to `true` in your TypeScript config (usually tsconfig.json)
- if you do not want TypeScript to process your `.js` files, in your Jest config change the `transform` key which value is `ts-jest`   so that it does not match `.js` files anymore

Ответы [ 2 ]

2 голосов
/ 02 октября 2019

попробуйте обновить "@ angular-builders / jest": "7.4.2" выглядит устаревшим

@ angular-builders / jest в настоящее время имеет версию 8.2.0.

Например:

npm install @angular-builders/jest@8.2.0 --dev

или использовать пряжу

yarn add @angular-builders/jest@8.2.0 --dev
0 голосов
/ 02 октября 2019

Ошибка была в операторе спреда - спред в undefined равен ошибка :

enter image description here

Как также объяснено здесь: Оператор распространения Javascript ES6 для неопределенного

Что странно для меня, что работало в Angular7 - возможно, оно предоставило пустое значение по умолчанию вместо undefined, если аргументы не были переданы в Angular pipe.

...