标签: babel-jest

带有ES6模块的babel-jest

我很高兴使用节点8.6,并打开了实验性的ES6模块选项(--experimental-modules).这使我能够完美地为节点编写简单的ES2015代码,而无需使用babel.

问题是当我尝试使用jest创建一些测试时,它无法抱怨语法错误:"意外的令牌导入".

.babelrc配置如下:

{
  "env": {
    "test": {
      "presets": [
        ["env", {
          "targets": {
            "node": "8.6"
          }
        }]
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我的jest.config.js如下:

module.exports = {
  testMatch: ['/tests/**/*.js', '**/?(*.)test.js'],
}
Run Code Online (Sandbox Code Playgroud)

抛出的错误:

    /app/tests/integration/controller/data-provider/Credentials/CredentialsList.action.test.js:2
    import { Credentials, AdWordsCredentials } from '../../../../../imports/models/data-provider/Credentials.mjs';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
          at Generator.next (<anonymous>)
          at Promise (<anonymous>)
Run Code Online (Sandbox Code Playgroud)

相关套餐:

  • babel-core@^6.26.0
  • jest@^21.2.1
  • babel-jest@^21.2.0
  • babel-preset-env@^1.6.0

任何帮助将不胜感激.谢谢 :)

更新:我尝试使用以下命令调用没有babel的jest,没有任何更改: node --experimental-modules node_modules/.bin/jest

babel ecmascript-6 jestjs babel-jest es6-modules

10
推荐指数
1
解决办法
1596
查看次数

需要Babel"^ 7.0.0-0",但加载了"6.26.0"

我已将我的应用程序迁移到babel 7 beta版,除了测试之外,一切似乎都有效.我想我已经阅读了所有内容,但我仍然收到此错误:

●测试套件无法运行

Requires Babel "^7.0.0-0", but was loaded with "6.26.0". If you are sure you have a compatible version of @babel/core, it is likely
Run Code Online (Sandbox Code Playgroud)

您的构建过程中的某些内容正在加载错误的版本.检查这个错误的堆栈跟踪,以寻找没有提到"@通天/芯"或"巴别塔芯",看看有什么在呼唤通天塔中的第一项.

  at throwVersionError (node_modules/@babel/helper-plugin-utils/lib/index.js:65:11)
  at Object.assertVersion (node_modules/@babel/helper-plugin-utils/lib/index.js:13:11)
  at _default (node_modules/@babel/plugin-proposal-class-properties/lib/index.js:81:7)
  at node_modules/@babel/helper-plugin-utils/lib/index.js:19:12
      at Array.map (<anonymous>)
Run Code Online (Sandbox Code Playgroud)

测试套房:8次失败,共8次

babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-flow"
  ],
  "plugins": [
    ["module-resolver", {
      "alias": {
        "static": "./static",
        "common": "./src/common",
        "data": "./src/data"
      }
    }],
    ["styled-jsx/babel", { "plugins": ["styled-jsx-plugin-sass"] }],
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-syntax-dynamic-import"
  ]
}
Run Code Online (Sandbox Code Playgroud)

devDependencies

  "devDependencies": {
    "@babel/cli": "^7.0.0-beta.49",
    "@babel/core": "^7.0.0-beta.49", …
Run Code Online (Sandbox Code Playgroud)

javascript babel jestjs babel-jest

10
推荐指数
1
解决办法
5095
查看次数

玩笑模拟未返回预期值

我发现我正在使用的模拟将返回一个字符串,它似乎返回jest.fn()而不是模拟的“实现” jest.fn().mockImplementation(...)

我这样称呼它:

const mockDefaultQuery = 'query { mock }'
jest.mock('../functions', () => (
{
    getArticle: jest.fn().mockName('getArticle').mockImplementation(() => {
        return {}
    }),
    defaultQuery: jest.fn().mockImplementation(() => {
        return mockDefaultQuery
    })
})
)
Run Code Online (Sandbox Code Playgroud)

但是从导入的“functions”库调用defaultQuery会在测试范围中返回[Function mockConstructor],而不是由它应该返回的const定义的“query {mock }”。

我也尝试过使用jest.fn().mockReturnValue(mockDefaultQuery)但没有效果。

jestjs babel-jest

9
推荐指数
1
解决办法
9186
查看次数

开玩笑 - `无法为组件创建样式组件:未定义`

使用测试我的应用程序时遇到以下错误jest

\n
 FAIL  \n  \xe2\x97\x8f Test suite failed to run\n\n    Cannot create styled-component for component: undefined.\n\n      30 |\n      31 | \n    > 32 | export const BackgroundVector = styled(Background)`\n         |                                 ^\n      33 |   position: fixed;\n      34 |   left: 0;\n      35 |   bottom: 0;\n
Run Code Online (Sandbox Code Playgroud)\n

Background是我在此文件顶部导入的 svg,如下所示:

\n
import { ReactComponent as Background } from \'../images/Background.svg\';\n
Run Code Online (Sandbox Code Playgroud)\n

我不太确定如何解决这个错误。在我的中package.json,我已将 SVG 文件映射到fileMock.js一个module.exports = \'test-file-stub\';. 我还应该做些什么来解决这个问题吗?

\n

jestjs babel-jest styled-components

9
推荐指数
1
解决办法
1万
查看次数

使用jest测试react-native app时,未定义XMLHttpRequest

我正在尝试使用jest(集成测试)在基于反应本机的应用程序中测试apiwrapper.当我在iOs模拟器中运行时,一切运行正常,但它不会正确运行我的开玩笑测试 - 我总是得到:

ReferenceError: XMLHttpRequest is not defined
Run Code Online (Sandbox Code Playgroud)

当我尝试使用我的api包装器运行测试时,例如:

it('Login successful with correct data', () => {
  let api = Api.getInstance();
  return api.login("test", "testpass")
         .then(result => expect(result).toEqual('login_successful'));
});
Run Code Online (Sandbox Code Playgroud)

我试图在这里测试的api类确实使用了fetch api(不是vanilla xhr).我假设它的某些东西与试图嘲笑某些东西有关,但还没有找到让它工作的方法.

提前致谢.

xmlhttprequest jestjs react-native babel-jest

8
推荐指数
1
解决办法
2791
查看次数

如何在JEST中测试DOM操作

我正在尝试测试ES6函数,该函数在执行时更新dom元素.目前我正在获取空节点列表,因为未加载HTML页面.用JEST纯粹测试这个的方法是什么?

jest.dontMock('../scripts/taskModel');
import Request from '../__mocks__/request';
import Task from '../scripts/taskModel';

describe('taskModel', () => {
    it('Should initialize with no friends items', function() {
        expect(document.querySelectorAll('.panel-block').length).toBe(1); // THIS IS ALWAYS RETURNS EMPTY NODELIST
        var task = new Task();
        task.index();
        expect(document.querySelectorAll('.panel-block').length).toBeGreaterThanOrEqual(6); // THIS IS ALWAYS RETURNS EMPTY NODELIST
    });
});
Run Code Online (Sandbox Code Playgroud)

jestjs babel-jest

8
推荐指数
1
解决办法
9508
查看次数

Jest模式"" - 0匹配(从jest 19 - > jest 20移动)

我正在使用以下jest.unittest.json文件(通过jest --config选项使用):

{
  "bail": false,
  "verbose": true,
  "transform": {
    "^.+\\.(ts|tsx)$": "typescript-babel-jest"
  },
  "testPathIgnorePatterns": [
    "<rootDir>/lib",
    "<rootDir>/lib_es6",
    "/node_modules/",
    "fixtures.ts",
    "/fixtures/"
  ],
  "moduleFileExtensions": [
    "js", "jsx", "ts", "tsx", "node"
  ],
  "roots": [
    "<rootDir>/src/__unittests__/Logger",
    "<rootDir>/src/__unittests__/Renderer/renderer.test.ts"
  ],
  "testRegex": "<rootDir>/src/__unittests__/.*\\.test.(ts|tsx|js|jsx)$"
}
Run Code Online (Sandbox Code Playgroud)

请注意,测试文件是src/unittests /Renderer/renderer.test.ts,依此类推.

它曾经工作到jest v19,但升级到v20后,此配置不再有效.

当我做jest --config jest.unittest.json --verbose时,我得到:

Pattern: "" - 0 matches

我的配置有什么问题吗?

jestjs babel-jest

8
推荐指数
1
解决办法
1717
查看次数

setupTests.js 未在 CRA 反应应用程序中自动加载

我已经读过 src/setupTests.js 应该在每次测试之前加载,但我仍然让每个测试失败并出现错误:

“酶内部错误:酶期望配置一个适配器,但没有找到。”

这是我的 src/setupTests.js

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'whatwg-fetch';

Enzyme.configure({ adapter: new Adapter() });
Run Code Online (Sandbox Code Playgroud)

这是我的 package.json:

"devDependencies": {
"babel-core": "^6.26.3",
"babel-jest": "^23.6.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"coveralls": "^3.0.2",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.6.0",
"enzyme-to-json": "^3.3.4",
"jest": "^23.6.0",
"react-test-renderer": "^16.5.2",
"redux-mock-store": "^1.5.3",
"regenerator-runtime": "^0.12.1",
"whatwg-fetch": "^3.0.0"
}
Run Code Online (Sandbox Code Playgroud)

我正在运行一个“测试”脚本 npm run test

"scripts": {
  "test": "jest",
  "test:watch": "jest --watch",
  "test:updateSnapshots": "jest --updateSnapshot"
}
Run Code Online (Sandbox Code Playgroud)

我使用以下某种形式开始每个测试文件:

import React from 'react';
import { shallow } from 'enzyme'; …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs enzyme babel-jest create-react-app

8
推荐指数
1
解决办法
4962
查看次数

带有jest + vuejs + vuetify的意外标识符

我一直在寻找答案。我怀疑这是一个.babelrc问题,但找不到有效的答案。

该应用程序运行正常,但据我发现,Jest和Rollup确实都依赖.babelrc。另一个可能的罪魁祸首是小叶。在我构建和测试的所有组件中,只有一个包含Leaflet的组件vue2-leaflet似乎有此问题。考虑到我正在开发地图绘制应用程序,这对我来说至关重要。

我在这里发帖,因为我什么都不能证明。还有许多其他人也遇到过类似的问题。

终端输出:

nr test:unit

> cxl-vue-leaflet@3.0.1-SNAPSHOT test:unit /Users/dan.mahoney/Projects/cxl-vue-leaflet
> NODE_ENV=testing BABEL_DISABLE_CACHE=1 jest --verbose --no-cache

Determining test suites to run...

# Starting...
# 1 test suites found.

#  FAIL  src/components/__test__/specs/cxl-vue-leaflet.spec.js

#
#   /Users/dan.mahoney/Projects/cxl-vue-leaflet/node_modules/vuetify/lib/index.js:1
#
#   ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Vuetify from './components/Vuetify';
#                                                                                                   ^^^^^^^
#
#   SyntaxError: Unexpected identifier
#
#   Stack:
#
#       at new Script (vm.js:85:7)

1..0

# Test Suites:  0%            , 1 failed, 1 total
# Tests:       0 total
# Time:        2.088s

# …
Run Code Online (Sandbox Code Playgroud)

vue.js jestjs babel-jest vuejs2 vuetify.js

8
推荐指数
1
解决办法
981
查看次数

jest 配置在更新到 26.x 后抛出“type ErrorHandler = (error: mixed, isFatal: boolean) =&gt; void”

我不知道为什么这突然不起作用,但这是我的 jest.config.js:

module.exports = {
  preset: 'react-native',
  verbose: true,
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  setupFiles: ['./jestSetup.js'],
  transformIgnorePatterns: [
    'node_modules/(?!(jest-)?react-native|@react-native-community|@react-navigation)',
  ],
  moduleNameMapper: {
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
  },
};
Run Code Online (Sandbox Code Playgroud)

和我的 jestSetup.js:

import 'react-native-gesture-handler/jestSetup';
import '@testing-library/jest-native/extend-expect';
import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock';

beforeAll(() => {
  //@ts-ignore
  global.__reanimatedWorkletInit = jest.fn();
});

jest.mock('react-native-share', () => ({
  default: jest.fn(),
}));

jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage);

jest.mock('react-native-reanimated', () => {
  const Reanimated = require('react-native-reanimated/mock');

  Reanimated.default.call = () => {};

  Reanimated.useSharedValue = jest.fn;
  Reanimated.useAnimatedStyle = jest.fn;
  return Reanimated;
});

jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper'); …
Run Code Online (Sandbox Code Playgroud)

jestjs react-native babel-jest

8
推荐指数
2
解决办法
2876
查看次数