Шут столкнулся с неожиданным токеном - Реагируйте с шуткой и энзимом - PullRequest
0 голосов
/ 05 марта 2020

tsconfig. json

{
    "extends": "./node_modules/pcf-scripts/tsconfig_base.json",
    "compilerOptions": {
        "typeRoots": ["node_modules/@types"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "sourceMap": true
    },
    "include": ["./ConsumptionSummaryComponent/src", "ConsumptionSummaryComponent/globals.d.ts"],
    "exclude": ["./node_modules/pcf-scripts/./node_modules"]
}

.babelr c файл

{
    "env": {
      "test": {
        "plugins": [
          "@babel/plugin-transform-modules-commonjs"
        ]
      }
    }
  }

Пакет. json

{
  "name": "pcf-project",
  "version": "1.0.0",
  "description": "Project containing your PowerApps Component Framework (PCF) control.",
  "scripts": {
    "build": "pcf-scripts build",
    "clean": "pcf-scripts clean",
    "rebuild": "pcf-scripts rebuild",
    "start": "pcf-scripts start",
    "test": "jest",
    "test:watch": "jest --watch"
  },
  "jest": {
    "roots": [
      "<rootDir>/ConsumptionSummaryComponent/src"
    ],
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.jsx$": "ts-jest"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "testEnvironment": "node",
    "setupFiles": [
      "<rootDir>/ConsumptionSummaryComponent/src/setupEnzyme.ts"
    ],
    "globals": {
      "ts-jest": {
        "tsConfig": "tsconfig.json",
        "babelConfig": "<rootDir>/ConsumptionSummaryComponent/.babelrc",
        "diagnostics": {
          "ignoreCodes": [
            "TS1149"
          ]
        }
      }
    },
    "collectCoverage": true,
    "coverageReporters": ["lcov"],
    "coverageDirectory": "test-coverage",
    "collectCoverageFrom": [
      "<rootDir>/ConsumptionSummaryComponent/src/components/**/*.{ts,tsx}",
      "<rootDir>/ConsumptionSummaryComponent/src/services/**/*.{ts,tsx}"
    ],
    "coverageThreshold": {
      "global": {
      "branches": 0,
      "functions": 0,
      "lines": 0,
      "statements": 0
      }
    },
    "moduleNameMapper": {
      "ts-jest": "<rootDir>/node_modules/ts-jest",
      "office-ui-fabric-react/lib/": "office-ui-fabric-react/lib-commonjs/",
      "@uifabric/fluent-theme/lib/": "@uifabric/fluent-theme/lib-commonjs/",
      "@uifabric/styling/lib/": "@uifabric/styling/lib-commonjs/",
      "expose-loader\\?jQuery\\!jquery": "<rootDir>/ConsumptionSummaryComponent/src/blank-mock",
      "^style-loader.*$": "<rootDir>/ConsumptionSummaryComponent/src/blank-mock",
      "^.*.svg$": "<rootDir>/src/blank-mock.js"
    },
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  },
  "dependencies": {
    "@apollo/react-hooks": "^3.1.3",
    "@common-pcf/sdk": "file:../sdk/common-pcf-sdk-1.0.0.tgz",
    "@microsoft/applicationinsights-web": "^2.3.1",
    "@types/node": "^10.12.18",
    "@types/powerapps-component-framework": "^1.2.0",
    "@uifabric/icons": "^7.3.2",
    "apollo-boost": "^0.4.7",
    "cra-template-typescript": "^1.0.0",
    "enzyme": "^3.11.0",
    "graphql": "^14.6.0",
    "graphql-tag": "^2.10.2",
    "office-ui-fabric-react": "^7.84.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10"
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "@graphql-codegen/introspection": "1.12.1",
    "@graphql-codegen/typescript": "1.12.1",
    "@graphql-codegen/typescript-operations": "1.12.1",
    "@graphql-codegen/typescript-react-apollo": "1.12.1",
    "@types/enzyme": "3.10.5",
    "@types/enzyme-adapter-react-16": "1.0.6",
    "@types/jest": "^25.1.1",
    "@types/react": "^16.9.19",
    "@types/react-dom": "^16.9.5",
    "babel-jest": "^25.1.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "enzyme-to-json": "3.4.4",
    "jest": "^25.1.0",
    "pcf-scripts": "^1",
    "pcf-start": "^1",
    "source-map-loader": "^0.2.4",
    "ts-jest": "25.1.0",
    "ts-loader": "^6.2.1"
  }
}

SetupEnzyme.ts

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

testcase

import * as React from "react";
import { shallow } from "enzyme";
import { DataModel } from "../../utils/DataModel";
import { styles } from "../../utils/style";
import { Enums } from "../../utils/enums";
import SummaryComponent from "../SummaryComponent";

const testProp: DataModel.ProductGroupSummaryViewModel = {
    consumptionText: "300 Subscriptions . 200 Active . $500 ACR",
    iconName: Enums.ProductTypeLogo.azureLogo,
    iconStyle: styles.AzureIcon,
    productGroupName: Enums.ProductTypeName.azureProductTypeName,
    isEnabled:true,
    order: 1
};

it("Should render the Summary component for the test Product Group Summary", () => {
    const result = shallow(<SummaryComponent {...testProp} />);
    expect(result).toMatchSnapshot();
});

Ошибка

Jest обнаружил неожиданный токен. Обычно это означает, что вы пытаетесь импортировать файл, который Jest не может проанализировать, например, это не просто JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

C:\DemandResponse\CSM-RCMND-DIGI-DigExp-UXWidgets\CSM-RCMND-DIGI-DigExp-UXWidgets\msp_RecommendationComponentSolution\ConsumptionSummaryComponent\ConsumptionSummaryComponent\src\setupEnzyme.ts:1
import { configure } from 'enzyme';
^^^^^^

SyntaxError: Cannot use import statement outside a module

It работает в другой системе, но не в моей системе. Каждая вещь является последней в моей системе. Пожалуйста, помогите мне с вопросом

1 Ответ

0 голосов
/ 05 марта 2020

отсутствует предустановка и нет необходимости в ферментном наборе быть файлом ts

потребует настройки jest для автономного файла, чтобы упростить жизнь:)

jest.config.js
module.exports = {
    collectCoverageFrom: [
        '<rootDir>/src/**/*.ts',
        '<rootDir>/src/**/*.tsx',
    ],
    moduleDirectories: ['node_modules', 'src'],
    testPathIgnorePatterns: ['<rootDir>/test/setup/'],
    setupFilesAfterEnv: ['<rootDir>/test/setup/setupEnzyme.js'],
    transform: {
        '\\.jsx?$': 'babel-jest',
    },
    transformIgnorePatterns: ['<rootDir>/node_modules/'],
    testRegex: 'test/.*\\.test\\.tsx?$',
    preset: 'ts-jest',
    moduleFileExtensions: ['ts', 'tsx', 'js'],
    moduleNameMapper: {
        '\\.(png)$': '<rootDir>/test/setup/fileMock.js',
        '\\.(css|less)$': '<rootDir>/test/setup/fileMock.js',
    },
};
  • собрать только покрытие для файлов ts и tsx.
  • преобразование всех файлов js и jsx с помощью babel-jest
  • применение предустановки ts-jest для файлов ts и tsx
  • макеты стилей и изображений с простым пустым js файлом.
setupEnzyme.js
require('@babel/polyfill');
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

Enzyme.configure({ adapter: new Adapter() });
...