我正在使用@testing-library/react-native 编写测试来呈现我的组件并在用户按下平面列表元素时测试 onPress 事件。我有一个包含几个元素的列表,但是,在其执行过程中,它的值更改为 undefined (我也不明白)。因此,当列表未定义时,它会尝试呈现未定义列表的元素。但是渲染应该只发生在if(myList !== undefined && myList !== null)
它仍然执行这个子句中的代码时。这是预期的行为吗?我怎样才能阻止它执行它?我还测试了 if 子句if(myList)
并具有相同的结果。
我的组件.js
const moods = useSelector(state => state.onboardingReducer.mood);
const renderMoods = (itemData) => {
console.log('I am on RENDER MOODS')
if(moods!==undefined && moods !== null){
console.log('moods ' + JSON.stringify(moods))
moodsCopy = [...moods];
}
const textStyle = (moodsCopy)? {backgroundColor: 'red'} : {backgroundColor: 'blue'}
return (<View>
<TouchableOpacity
onPress={handleOnPress.bind(this, itemData.item)}>
<Text style={textStyle} data-testid="text">{itemData.item.title}</Text>
</TouchableOpacity>
</View>);
};
myComponent-test.js
import { render, fireEvent, waitForElementToBeRemoved } from '@testing-library/react-native';
describe('events', () => {
test('On press to remove item', async () => {
useSelector.mockReturnValueOnce(userInfo).mockReturnValueOnce([
{name: 'Happy', id: '111'},
{name: 'In Love', id:'111'}
]);
const { getByText, getByTestId, debug } = render(<MoodList {...props}/>);
}
}
在我的控制台上,我得到:
moods [{"name":"Happy","id":"111"},{"name":"In Love","id":"111"}]
I am on RENDER MOODS
moods undefined
I am on RENDER MOODS
最后我得到一个错误:
TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.