简体   繁体   English

Jest 遇到意外令牌 - 与 Jest 和酶反应

[英]Jest encountered an unexpected token - React with jest and enzyme

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"]
}

.babelrc file .babelrc 文件

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

Package.json包.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设置Enzyme.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();
});

Error错误

Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, eg it's not plain JavaScript. 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 is working in other system but not in my system.它在其他系统中有效,但在我的系统中无效。 Every thing is latest in my system.我的系统中的每件事都是最新的。 Kindly help me with the issue请帮我解决这个问题

missing preset and no need for enzymeSetup to be ts file缺少预设并且不需要酶设置是 ts 文件

would take the jest configuration to stand alone file to make life easier :)会将 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',
    },
};
  • collect coverage only for ts and tsx files.仅收集 ts 和 tsx 文件的覆盖范围。
  • transform all js and jsx files via babel-jest通过babel-jest转换所有 js 和 jsx 文件
  • apply preset ts-jest for ts and tsx files为 ts 和 tsx 文件应用预设ts-jest
  • mock styles and images with plain empty js file.使用纯空 js 文件模拟样式和图像。
setupEnzyme.js
require('@babel/polyfill');
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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