【问题标题】:Cannot read property 'items' of undefined无法读取未定义的属性“项目”
【发布时间】:2017-11-02 20:16:05
【问题描述】:

我是 Jest + Enzyme 的新手,我一直在我的应用程序中进行一些测试,一切都很好,直到我尝试在我的一个组件中测试 onPress 事件,该组件呈现一个内部有 ListItem 的 ScrollView。错误是:Cannot read property 'items' of undefined

下面是我的代码:

List.js

import React from 'react';
import { Text, StyleSheet, Image, View, ScrollView, Alert} from 'react-native';
import { ListItem, Button, Card } from 'react-native-elements'
import {observer, inject} from 'mobx-react';
import {StackNavigator} from 'react-navigation';

@inject('ItemStore')
@observer
export default class List extends React.Component{
 constructor(props){
     super(props);
     this.state = {
        itemsSelected: [],
    }
  }

  displayItem(item, index){
    const {navigate} = this.props.navigation;             
    this.props.ItemStore.ItemStore.itemSelected(item);
    navigate("OtherComp", {'index': index});
  }

  render(){
    return(
        <ScrollView>
                {
                    this.props.ItemStore.items.length ?
                    this.props.ItemStore.items.map((item, i) => (
                        <ListItem roundAvatar avatar = {{uri: item.photo_uri}} 
                                  title = {item.name}
                                  key = {i}
                                  onPress = {this.displayItem.bind(this, item, i)} 
                                  onLongPress = {this.setitem.bind(this, i)}
                                  containerStyle = {{ backgroundColor: this.state.itemsSelected.indexOf(i) >= 0 ? "#f1f1f1" : "#ffffff"}}
                        />
                    )) : undefined
                }   
        </ScrollView>
    );
 }

} 

List.test.js

import 'react-native';
import React from 'react';
import Enzyme from 'enzyme';
import MyList from '../../components/list/List';
import {shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import sinon from 'sinon';
import { ListItem } from 'react-native-elements'

const ItemStore = require('../../stores/ItemStore').default;

Enzyme.configure({adapter: new Adapter()});

describe('ItemList', () => {
it('click list item', () => {
    const wrapper = shallow(<MyList ItemStore={ItemStore.ItemStore} />)        
    const render = wrapper.dive();
    const displayItem = sinon.spy(MyList, "displayItem");
    render.find(ListItem).forEach(child => {
        child.simulate('onPress');
    });
    expect(displayItem.calledOnce).toBe(true);
 });
});

我正在使用多个商店,这就是为什么调用它是store.store

【问题讨论】:

  • 该列表引用在哪个文件/行中?您发布的代码中没有对该变量的单一引用。
  • 我更新了帖子,它是项目而不是列表,并且在这一行 this.props.ItemStore.items.length

标签: react-native enzyme jestjs


【解决方案1】:

不应该这样吗:

this.props.ItemStore.items.length

成为..

this.props.ItemStore.ItemStore.items.length ?

【讨论】:

  • 我这样做了,但没有结果,问题似乎在测试中,应用程序运行良好,但是当我运行测试时出现错误,我尝试使用 mount 但结果相同
猜你喜欢
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
  • 2022-06-19
相关资源
最近更新 更多