我正在为我的应用创建测试,并且在Jest中运行它们时遇到问题。我的代码结构如下:
<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>
&#13;
我正在尝试运行FormElement(FormElement.test.js)组件的测试。内部测试我有一个import语句:
import DepartmentsSearch from '../../../../containers/DepartmentsSearch/DepartmentsSearch'
我的DepartmentSearch是一个使用react-reactx库连接的容器。
import DepartmentSelector from '../../components/DepartmentSelector/DepartmentSelector'
import {createDepartment} from '../../actions'
const mapStateToProps = (state) => {
return {
departments: state.departments
}
}
export default connect(mapStateToProps, {createDepartment})(DepartmentSelector)
&#13;
由于某种原因import DepartmentSelector
返回undefined而不是react组件(它只是一个哑组件而不是容器)。最奇怪的是,只有在运行测试而不是在浏览器中运行代码时才会发生这种情况。我一开始就试图使用顶级进口,但也失败了。
import {DepartmentSelector} from '../../components'
我没有其他的想法,为什么它可能只是在测试时失败,如果有人能指出我正确的方向,我会很高兴。
答案 0 :(得分:2)
问题在于如何导入依赖项。在这种情况下,DepartmentSelector
会导入Form
,导入FormElement
和FormElement
导入DepartmentSearch
(我们的容器)。因为节点不知道如何导入是依赖(递归依赖),它只返回一个错误。它在Web浏览器中工作,因为webpack非常好地处理递归依赖,并从代码中提取它们。解决该问题的最简单的解决方案是在测试文件的顶部导入DepartmentSearch
// DepartmentSelector.test.js
import DepartmentSearch from '../../containers/DepartmentSearch/DepartmentSearch'
答案 1 :(得分:0)
您的DepartmentSearch
没有render()
方法,也没有返回任何内容(因此“未定义”)。
您需要至少通过render()
返回一些内容,无论是儿童节点,false
还是null
。否则,应用程序的其余部分不知道如何处理组件。