1

我正在尝试使用酶和玩笑为反应原生组件编写基本测试。我收到一个错误,暗示没有正确导入酶:

● SearchPage › it starts spinner when page is loading
  - ReferenceError: _enzyme is not defined
        at Spec.eval (__tests__/basic-test.js:12:16)
1 test failed, 0 tests passed (1 total in 1 test suite, run time 1.113s)
npm ERR! Test failed.  See above for more details.

由于我是新手,我尝试过重新安装酶包并盲目地摆弄代码。不使用来自酶工作的浅层的基本测试,即expect(true).toBe(true)。我已经浏览了很多关于 JS 中的 referenceErrors 的问题,但似乎没有一个适用于这种情况(无论如何,在我没有经验的眼里)。

这是测试文件。非常简单,限制了错误的来源。

jest.dontMock('../SearchPage');

import React from 'react';
import { shallow } from 'enzyme';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';

const SearchPage = require('../SearchPage');

describe('SearchPage', () => {
  it('starts spinner when page is loading', () => {
    const wrapper = shallow(<SearchPage />);

    // Check that it is false initially i.e. not loading.
    expect(wrapper.state('isLoading')).toBe(false);

    // Simulate a touch on 'Go' button and verify loading is now true
  });
});

据我所知,我的 package.json 具有正确的依赖关系。我试过重新安装酶但没有成功。这里是:

{
  "name": "PropertyFinder",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react-native": "^0.20.0",
    "react-dom": "~0.14.7"
  },
  "devDependencies": {
    "babel-jest": "*",
    "enzyme": "^2.0.0",
    "jest-cli": "^0.8.2",
    "react": "^0.14.7",
    "react-addons-test-utils": "~0.14.0",
    "react-native-mock": "0.0.6"
  },
  "jest": {
    "scriptPreprocessor": "node_modules/react-native/jestSupport/preprocessor.js",
    "setupEnvScriptFile": "node_modules/react-native/jestSupport/env.js",
    "testPathIgnorePatterns": [
      "/node_modules/",
      "packager/react-packager/src/Activity/"
    ],
    "testFileExtensions": [
      "js"
    ],
    "unmockedModulePathPatterns": [
      "promise",
      "source-map",
      "react",
      "react-dom",
      "react-addons-test-utils",
      "fbjs",
      "enzyme",
      "cheerio",
      "htmlparser2",
      "lodash",
      "domhandler",
      "object.assign",
      "define-properties",
      "function-bind",
      "object-keys",
      "object.values",
      "es-abstract"
    ]
  }
}

在这种情况下可能/会抛出这个 ReferenceError 是什么?如果我尝试 mocha/chai 看看是否可行,我可能会很快发表评论,但我宁愿在这一点上继续开玩笑。

4

1 回答 1

0

这个问题源于 ES6 中的导入提升,这里有更详细的解释。使用 babel-jest 作为预处理器将解决这个问题,但保留“setupEnvScriptFile”很重要。

对我有用的示例

"jest": {
    "preprocessorIgnorePatterns": [
      "node_modules/enzyme"
    ],
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "setupEnvScriptFile": "node_modules/react-native/jestSupport/env.js",
    "testPathIgnorePatterns": [
      "/node_modules/",
      "packager/react-packager/src/Activity/"
    ],
    "unmockedModulePathPatterns": [
      "react",
      "react-dom",
      "react-native",
      "react-addons-test-utils",
      "promise",
      "source-map",
      "enzyme"
    ]
  },
于 2016-04-22T02:17:48.553 回答