代码之家  ›  专栏  ›  技术社区  ›  piro

测试时,导入返回未定义的组件,而不是react组件

  •  3
  • piro  · 技术社区  · 9 年前

    我正在为我的应用程序创建测试,在开玩笑地运行它们时遇到了问题。我的代码结构如下所示:

    <pre>
    ./src/
    ├── actions
    │   ├── departments.js
    │   ├── departments.test.js
    ├── actionTypes
    │   ├── departmentsTypes.js
    ├── components
    │   ├── common
    │   │   ├── Form
    │   │   │   ├── Form.css
    │   │   │   ├── FormElement
    │   │   │   │   ├── FormElement.css
    │   │   │   │   ├── FormElement.js
    │   │   │   │   ├── FormElement.test.js
    │   │   │   │   └── __snapshots__
    │   │   │   ├── Form.js
    │   │   │   ├── Form.test.js
    │   │   │   ├── index.js
    │   │   │   └── __snapshots__
    │   │   │       └── Form.test.js.snap
    │   │   ├── index.js
    │   │   ├── SchemaFormFactory
    │   │   │   ├── SchemaFormFactory.js
    │   │   │   ├── SchemaFormFactory.test.js
    │   │   │   └── __snapshots__
    │   │   │       └── SchemaFormFactory.test.js.snap
    │   │   └── TextInput
    │   ├── DepartmentSelector
    │   │   ├── DepartmentSelector.css
    │   │   ├── DepartmentSelector.js
    │   │   ├── DepartmentSelector.test.js
    │   │   ├── index.js
    │   │   └── __snapshots__
    │   ├── index.js
    │   ├── MainApp
    │   │   ├── index.js
    │   │   ├── MainApp.css
    │   │   ├── MainApp.js
    │   │   ├── MainApp.test.js
    │   │   └── __snapshots__
    ├── containers
    │   ├── DepartmentForm
    │   │   └── DepartmentForm.js
    │   ├── DepartmentsSearch
    │   │   ├── DepartmentsSearch.js
    │   │   ├── DepartmentsSearch.test.js
    │   │   ├── index.js
    │   │   └── __snapshots__
    ├── helpers
    │   └── test-helper.js
    ├── index.js
    ├── reducers
    │   ├── departments.js
    │   ├── departments.test.js
    </pre>

    我正在尝试对FormElement(FormElement.test.js)组件进行测试。内部测试我有一个导入语句:

    import DepartmentsSearch from '../../../../containers/DepartmentsSearch/DepartmentsSearch'
    

    我的DepartmentSearch是一个容器,它使用react redux库中的connect。

    import DepartmentSelector from '../../components/DepartmentSelector/DepartmentSelector'
    import {createDepartment} from '../../actions'
    
    const mapStateToProps = (state) => {
      return {
        departments: state.departments
      }
    }
    
    export default connect(mapStateToProps, {createDepartment})(DepartmentSelector)

    出于某种原因 import DepartmentSelector import {DepartmentSelector} from '../../components'

    2 回复  |  直到 9 年前
        1
  •  3
  •   piro    9 年前

    问题在于如何导入依赖项。在这种情况下 DepartmentSelector 导入a Form 哪些进口 FormElement 和 进口 DepartmentSearch (我们的集装箱)。因为节点不知道如何导入依赖项(递归依赖项),所以它只返回一个错误。它在web浏览器中工作,因为webpack可以很好地处理递归依赖项,并从代码中提取它们。解决该问题的最简单解决方案是导入 部门搜索

    // DepartmentSelector.test.js
    import DepartmentSearch from '../../containers/DepartmentSearch/DepartmentSearch'
        2
  •  0
  •   Justin Pearce    9 年前

    DepartmentSearch 没有 render() 方法,并且不返回任何内容(因此为“未定义”)。

    render() false 或 null