2016-03-21 2 views
1

Можете ли вы, ребята, помочь мне решить эту проблему. У меня есть два файла .jsx, импортированных под другим. Позволяет сказать, A.jsx (Внутри A.jsx я импортирован B.jsx) B.jsxМодуль не найден: Ошибка: не удается разрешить «файл» или «каталог»

Когда оба файлы записаны под тот же файл в этом случае блок тестов работает нормально. В тот момент, когда я отделяю его, компонент работает нормально, но блок-тесты не работают. Webpack карма бросает ошибку говоря

ERROR in ./src/components/thpfooter/index.jsx Module not found: Error: Cannot resolve 'file' or 'directory' ./ThpFooterList in /Users/zi02/projects/creps_ui_components_library/src/components/thpfooter @ ./src/components/thpfooter/index.jsx 9:1725-1751

karma.conf.js
/*eslint-disable*/ 
var webpack = require('karma-webpack'); 
var argv = require('yargs').argv; 
var componentName = "**"; 
if (typeof argv.comp !== 'undefined' && argv.comp !== null && argv.comp !== "" && argv.comp !== true) { 
    componentName = argv.comp; 
} 

var testFiles = 'src/components/'+componentName+'/test/*.js'; 
var mockFiles = 'src/components/'+componentName+'/test/mock/*.json'; 

module.exports = function (config) { 
    config.set({ 
    frameworks: ['jasmine'], 
    files: [ 
     './node_modules/phantomjs-polyfill/bind-polyfill.js', 
     testFiles, 
     mockFiles 
    ], 
    plugins: [webpack, 
       'karma-jasmine', 
       'karma-phantomjs-launcher', 
       'karma-coverage', 
       'karma-spec-reporter', 
       'karma-json-fixtures-preprocessor', 
       'karma-junit-reporter'], 
    browsers: ['PhantomJS'], 
    preprocessors: { 
     'src/components/**/test/*.js': ['webpack'], 
     'src/components/**/*.jsx': ['webpack'], 
     'src/components/**/test/mock/*.json': ['json_fixtures'] 
    }, 
    jsonFixturesPreprocessor: { 
     // strip this from the file path \ fixture name 
     stripPrefix: 'src/components/', 
     // strip this to the file path \ fixture name 
     prependPrefix: '', 
     // change the global fixtures variable name 
     variableName: '__mocks__', 
    // camelize fixture filenames 
    // (e.g 'fixtures/aa-bb_cc.json' becames __fixtures__['fixtures/aaBbCc']) 
     camelizeFilenames: true, 
     // transform the filename 
     transformPath: function (path) { 
     return path + '.js'; 
     } 
    }, 
    reporters: ['spec', 'coverage','junit'], 
    coverageReporter: { 
     dir: 'build/reports/coverage', 
     reporters: [ 
     { type: 'html', subdir: 'report-html' }, 
     { type: 'lcov', subdir: 'report-lcov' } 
     ] 
    }, 
    junitReporter: { 
     outputDir: 'build/reports/coverage/junit/'+componentName, 
     suite: '' 
    }, 

    webpack: { 
     module: { 
     loaders: [{ 
      test: /\.(js|jsx)$/, exclude: /node_modules/, 
      loader: 'babel-loader' 
     }], 
     postLoaders: [{ 
      test: /\.(js|jsx)$/, exclude: /(node_modules|test)/, 
      loader: 'istanbul-instrumenter' 
     }] 
     } 
    }, 
    webpackMiddleware: { noInfo: true } 
    }); 
}; 

footer.jsx

import React from 'react'; 
import ThpFooterList from './ThpFooterList'; 

class ThpFooter extends React.Component { 
    //footer code here 
} 

ThpFooterList.jsx
import React from 'react'; 

class ThpFooterList extends React.Component { 
    //footer list code here 
} 

Смотрите выше ком ponent работает, но я не могу выполнить единичный тестовый пример. Когда вы сохраняете оба из них в одном файле, подразумевается нижний колонтитул и footerlist.jsx, тогда выполняются компоненты, а также единичные тестовые примеры.

случае файл модульного тестирования

/* eslint-env jasmine */ 
import React from 'react'; 
import TestUtils from 'react/lib/ReactTestUtils'; 

import ThpFooter from '../index.jsx'; 


describe('ThpFooter',() => { 
    let component; 
    let content; 
    let shallowRenderer; 
    let componentShallow; 

    beforeAll(() => { 
    content = window.__mocks__['thpfooter/test/mock/content']; 
    component = TestUtils.renderIntoDocument(<ThpFooter data={content}/>); 
    shallowRenderer = TestUtils.createRenderer(); 
    shallowRenderer.render(<ThpFooter data={content}/>); 
    componentShallow = shallowRenderer.getRenderOutput(); 
    }); 

    describe('into DOM',() => { 
    it('Should be rendered into DOM',() => { 
     expect(component).toBeTruthy(); 
    }); 

    it('Should have classname as footer-container',() => { 
     const classname = TestUtils.scryRenderedDOMComponentsWithClass(component, 'footer-container'); 
     expect(classname[0].className).toBe('footer-container'); 
    }); 

    it('Should have className as footer-wrapper',() => { 
     const classname = TestUtils.scryRenderedDOMComponentsWithClass(component, 'footer-wrapper'); 
     expect(classname[0].className).toBe('footer-wrapper'); 
    }); 
    }); 

    describe('into shallow renderer',() => { 
    it('Should be rendered as shallow renderer',() => { 
     expect(componentShallow).toBeTruthy(); 

    }); 

    it('Should have classname as footer-container',() => { 
     expect(componentShallow.props.className).toBe('footer-container'); 
    }); 

    it('Should have className as footer-wrapper',() => { 
     expect(componentShallow.props.children.props.children[0].props.className).toBe('footer-wrapper'); 
    }); 
    }); 

}); 
+1

код, код, код. Отправьте свой код при обращении за помощью. – Andreyco

+0

@ Андреко: найдите обновленный вопрос. Благодаря!!! –

ответ

0

я испытал ту же самую ошибку на одной из машин развития. Хотя в моем случае использовался gulp и webpack-stream, я думаю, вы можете ссылаться на мой метод, чтобы попытаться его решить.

На моем Mac все хорошо, но когда я подтолкнул код к платформе разработки ubuntu, эта проблема была замечена. После некоторого googling я не могу его решить, но затем я попытался сделать путь к файлу короче, а затем внезапно он тоже работает на платформе разработки ubuntu! Вы можете попытаться сократить имя файла или поместить его в более короткий путь и проверить, работает ли он.

+0

Путь к файлу короче и странно, что компонент работает, но только единичные тестовые примеры терпят неудачу. Даже я использую Mac-машину для разработки. :) –

+0

Я обнаружил, что моя проблема в том, что файловая система на маке нечувствительна к регистру, а система Linux - чувствительна к регистру. Я думаю, проблема заключается в строке 'import ThpFooter из '../ index.jsx';' и файл не может быть разрешен из этого файла index.jsx – redcomethk

+0

его не из-за нечувствительности к регистру @redcomethk –

0

Часы для чувствительности к регистру. Файловая система Mac не чувствительна к регистру, Windows/Linux.

+0

Нет, это не из-за этого i проверили его много раз –

Смежные вопросы