Проблемы при запуске объекта Web API File в тесте с Babel и Jest - PullRequest
2 голосов
/ 03 ноября 2019

При попытке обновить babel до v7 в существующей тестовой конфигурации с Jest и Enzyme я столкнулся с проблемой, когда Файл Web API пуст. Хотя он отвечает на такие методы, как myFile.name.

Используемые пакеты:

  • babel => 7.6.4
  • jest => 24,9.0
  • babel-jest => 24.9.0

Не совсем эксперт с babel, но это мой конфиг

Конфигурация детки

const env = process.env.NODE_ENV;
const isProd = () => env === 'production';
const isDev = () => env === 'development';
const isTest = () => env === 'test';

const babelPresetEnvOptions = () => {
    const options = {};

    if (isTest()) {
        options.targets = { node: 'current' };
    } else {
        // Disable polyfill transforms
        options.useBuiltIns = false;
        // Do not transform modules to CommonJS
        options.modules = false;
    }

    if (isProd()) {
        options.forceAllTransforms = true;
    }

    return options;
};

const presets = [
    [require.resolve('@babel/preset-env'), babelPresetEnvOptions()],
    [require.resolve('@babel/preset-react'), { development: isDev() }],
];

const plugins = [
    [require.resolve('@babel/plugin-proposal-decorators'), { legacy: true }],
    [require.resolve('@babel/plugin-proposal-class-properties'), { loose: true }],
    require.resolve('@babel/plugin-proposal-object-rest-spread'),
    require.resolve('@babel/plugin-transform-react-jsx'),
    require.resolve('@babel/plugin-transform-runtime'),
];

if (isTest()) {
    // Compiles import() to a deferred require()
    plugins.push(require.resolve('babel-plugin-dynamic-import-node'));
} else {
    // Adds syntax support for import()
    plugins.push(require.resolve('@babel/plugin-syntax-dynamic-import'));
}

module.exports = api => {
    api.assertVersion('^7.6');

    return {
        presets,
        plugins,
    };
};

Настройка Jest

  "jest": {
    "rootDir": "./webpack",
    "setupFiles": [
      "<rootDir>/test/jestsetup.js"
    ],
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "moduleNameMapper": {
      "^.+\\.(css|scss)$": "identity-obj-proxy"
    },
    "transform": {
      "^.+\\.(js|jsx)?$": "babel-jest"
    }
  },

Проблема: Когда я пытаюсь инициировать объект файла

const lastModified = 1511256180536;
const myImageFile = new File([''], 'pixel.gif', { type: 'image/gif', lastModified });
console.log(myImageFile); // Also results in => File {}
console.log(imageFile.name); // return 'pixel.gif'

Тестовый снимок завершается неудачно, как показано ниже, и я не могу объяснить, почему.

-     file={
-       File {
-         Symbol(impl): FileImpl {
-           "_buffer": Object {
-             "data": Array [],
-             "type": "Buffer",
-           },
-           "isClosed": false,
-           "lastModified": 1511256180536,
-           "name": "pixel.gif",
-           "type": "image/gif",
-           Symbol(wrapper): [Circular],
-         },
-       }
-     }
+     file={File {}}

Даже намек на это был бы полезен.

Отладка Babel

@babel/preset-env: `DEBUG` option

Using targets:
{
  "node": "12.11"
}

Using modules transform: auto

Using plugins:
  syntax-async-generators { "node":"12.11" }
  syntax-object-rest-spread { "node":"12.11" }
  syntax-json-strings { "node":"12.11" }
  syntax-optional-catch-binding { "node":"12.11" }
  transform-modules-commonjs { "node":"12.11" }
  proposal-dynamic-import { "node":"12.11" }

Using polyfills: No polyfills were added, since the `useBuiltIns` option was not set.
...