SearchResult(...):渲染未返回任何内容。这通常意味着缺少return语句。或者,不渲染任何内容,则返回null

时间:2020-05-31 15:37:08

标签: reactjs null render react-testing-library

在这一部分中,我正在编写测试,并尝试通过检查其中是否存在数组来测试此组件。如您所见,错误弹出,并显示return语句丢失。它正在测试组件内部的render方法。请记住,我使用的是哑组件,因此可以更轻松地测试该组件。

const utils = render(<Provider store={store}><SearchResult/></Provider>);

已经导入了提供商和商店,但仍然没有成功,所以我想知道我还能做什么。

import React from 'react'
import { render, fireEvent } from '@testing-library/react';
import { SearchResult } from './SearchResult';
import { Provider } from 'react-redux';
import { store } from './Store';

const setup = () => {
    const utils = render(<Provider store={store}><SearchResult/></Provider>); <---- nagging 
    const buttons = utils.getByLabelText('search-result');
    return {
        buttons,
        ...utils
    }
}

test('It should keep a $ in front of the input', () => {
    const { buttons } = setup()
    fireEvent.click(buttons)
    expect(buttons.getByLabelText).toBe(null)
})

import React from 'react';
import { useDispatch } from 'react-redux';
import { openIngredient } from '../actions/index';
import { connect } from 'react-redux';

export const SearchResult = ({ ingredientButtons }) => {
    const dispatch = useDispatch();

    const buttons = ingredientButtons;
    if(buttons === undefined) return;

    const allButtons = buttons.map((ingredientBtn, i) => {
        if(ingredientBtn == null) {
            return false;
        }
        return (
            <div key={i}>
                <button aria-label="search-result" onClick={() => dispatch(openIngredient(ingredientBtn))}>{ingredientBtn.strMeal}</button>
            </div>
        )
    })

    return (
        <div>
            {allButtons}
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        ingredientButtons: state.getData.allSearchButtons || undefined
    }
}

export default connect(mapStateToProps, null)(SearchResult);

1 个答案:

答案 0 :(得分:0)

仔细阅读错误消息=)

这是问题所在

    if(buttons === undefined) return;

您在此处不返回任何内容,这意味着未定义将隐式返回。

根据错误消息,您应该返回null