2016-11-07 4 views
3

У меня есть среагировать проект, и я пытаюсь настроить некоторые тестыНастройка шутя и энзим, чтобы проверить Реагировать 15 не может найти модуль реагировать/Lib/ReactTestUtils

Благодаря следующим гидам настройки/вопросы:

Я установил следующие зависимости:

  • реагирующие-аддоны тест-Utils 15.3.2
  • реагируют 15.4.0-rc.4
  • реагируют-15.4.0 дом-RC -4
  • шутка 16.0.2
  • Бабель-шутка 16.0.0
  • Бабель-запрограммированный-es2015 6.18.0
  • Бабель-пр ESET-es2015-рыхлый 7.0.0
  • столпотворение-предустановленным реагируют 6.16.0

Мой package.json содержит следующую конфигурацию: шутя

"jest": { 
    "bail": false, 
    "collectCoverage": true, 
    "collectCoverageFrom": [ 
     "<rootDir>/src/**/*.js", 
     "!<rootDir>/node_modules/**" 
    ], 
    "coverageDirectory": "coverage", 
    "coveragePathIgnorePatterns": [ 
     "<rootDir>/node_modules" 
    ], 
    "coverageThreshold": { 
     "global": { 
     "branches": 50, 
     "functions": 50, 
     "lines": 50, 
     "statements": 50 
     } 
    }, 
    "globals": { 
     "SOURCEMAP": true 
    }, 
    "modulePaths": [ 
     "<rootDir>/src", 
     "<rootDir>/sass", 
     "<rootDir>/public", 
     "<rootDir>/node_modules" 
    ], 
    "resetModules": true, 
    "testPathDirs": [ 
     "<rootDir>/test" 
    ], 
    "testRegex": "(/test/.*|\\.(test|spec))\\.(js|jsx)$", 
    "verbose": true 
    } 

У меня есть компонент (GenericButton) помещен в <rootDir>/components/buttons/GenericButton.js и мой тест в <rootDir>/test/componnets/buttons/GenericButtonTest.js с содержимым в следующем:

import React from 'react'; 
import GenericButton from 'components/buttons/GenericButton'; 
import { shallow } from 'enzyme'; 
import { shallowToJson } from 'enzyme-to-json'; 
import ReactTestUtils from 'react-addons-test-utils' 

describe('Generic Button',() => { 
    test('Button action called when clicked',() => { 
     var clicked = false; 
     const component = shallow(
      <GenericButton action={() => { 
       clicked = true; 
      }}/> 
     ); 

     console.log("Clicking the button!"); 
     ReactTestUtils.Simulate.click(component); 
     expect(clicked).toBeTruthy(); 
    }); 
}) 

Мой файл babelrc выглядит следующим образом:

{ 
    "presets": [ 
    "es2015-loose", 
    "react", 
    "stage-0" 
    ], 
    "plugins": [ 
    "babel-root-slash-import", 
    "transform-decorators-legacy", 
    "react-hot-loader/babel", 
    "transform-runtime" 
    ], 
    "compact": true, 
    "ignore": [ 
    "/node_modules/(?!react-number-input)" 
    ] 
} 

когда я бегу мое испытание, однако, я получаю следующее сообщение об ошибке:

> [email protected] test C:\path\to\project 
> jest 

FAIL test\components\buttons\GenericButtonTest.js 
    ● Test suite failed to run 

    Cannot find module 'react/lib/ReactTestUtils' from 'index.js' 

     at Resolver.resolveModule (node_modules\jest-resolve\build\index.js:144:17) 
     at Object.<anonymous> (node_modules\react-addons-test-utils\index.js:1:107) 
     at node_modules\enzyme\build\react-compat.js:128:19 

----------|----------|----------|----------|----------|----------------| 
File  | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines | 
----------|----------|----------|----------|----------|----------------| 
All files | Unknown | Unknown | Unknown | Unknown |    | 
----------|----------|----------|----------|----------|----------------| 
Test Suites: 1 failed, 1 total 
Tests:  0 total 
Snapshots: 0 total 
Time:  5.843s 
Ran all test suites. 
    console.error node_modules\enzyme\build\react-compat.js:131 
    react-addons-test-utils is an implicit dependency in order to support [email protected] Please add the appropriate version to your devDependencies. See https://github.com/airbnb/enzyme#installation 

npm ERR! Test failed. See above for more details. 

Что я могу сделать, чтобы сделать этот простой тест пройти?


Edit: Файл реагировать/Библиотека/ReactTestUtils реагирующие-аддонов-тест-Utils требует, не в node_modules/среагировать/Lib папку.

Это было исправлено путем обновления реагирующие-аддоны-тест-утилиты для 15.4.0-rc.3, но потом я получил:

TypeError: Cannot read property '__reactInternalInstance$t476n6b4jes0zxw0n18vbzkt9' of undefined 

    at getClosestInstanceFromNode (node_modules\react-dom\lib\ReactDOMComponentTree.js:106:11) 
    at Object.getInstanceFromNode (node_modules\react-dom\lib\ReactDOMComponentTree.js:140:14) 
    at Object.click (node_modules\react-dom\lib\ReactTestUtils.js:326:74) 
    at Object.<anonymous> (test\components\buttons\GenericButtonTest.js:17:67) 

ответ

3

Вы не можете использовать ReactTestUtils и enzyme вместе в тесте на момент. К счастью, вы можете имитировать щелчок с помощью фермента. Единственная проблема заключается в том, что simulate не распространяется на дочерние компоненты компонентов, поэтому вам нужно сначала найти ребенка и вызвать на нем simulate.

import React from 'react'; 
import GenericButton from 'components/buttons/GenericButton'; 
import { shallow } from 'enzyme'; 
import { shallowToJson } from 'enzyme-to-json'; 

describe('Generic Button',() => { 
    test('Button action called when clicked',() => { 
     var clicked = false; 
     const component = shallow(
      <GenericButton action={() => { 
       clicked = true; 
      }}/> 
     ); 
     component.find('selectrorOfChildWithClickHandler').first().simulate('click') 
     expect(clicked).toBeTruthy(); 
    }); 
}) 
+0

ReferenceError: click не указан -------- у объекта. (test \ components \ buttons \ GenericButtonTest.js: 18: 42) -------- на process._tickCallback (internal \ process \ next_tick.js: 103: 7) – mangusbrother

+0

В моем ответе есть опечатка , –

+0

эта ошибка решён. now: Метод «реквизит» предназначен только для запуска на одном узле. 0 найдено. ----- на ShallowWrapper.single (node_modules \ ferry \ build \ ShallowWrapper.js: 1401: 17) ----- на ShallowWrapper.props (node_modules \ ferry \ build \ ShallowWrapper.js: 791: 21) ----- на ShallowWrapper.prop (node_modules \ ferry \ build \ ShallowWrapper.js: 997: 21) ----- на ShallowWrapper.simulate (node_modules \ ferry \ build \ ShallowWrapper.js: 762: 28) ----- у объекта. (test \ components \ buttons \ GenericButtonTest.js: 17: 33) ----- на process._tickCallback (internal \ process \ next_tick.js: 103: 7) – mangusbrother

1

Фермент нуждается в этих зависимостей:

npm i --save-dev enzyme 
npm i --save-dev react-addons-test-utils 
npm i --save-dev react-dom 

быть установлен как devDependencies. Это сработало для меня.