ReferenceError:渲染未在onChange输入React测试库中定义

时间:2020-05-30 17:44:17

标签: reactjs jestjs react-testing-library

作为一个菜鸟,我完全坚持在Jest中进行测试。终端为何显示referenceErrror,render尚未定义。即使当我从@ testing-library / react导入该文件时,下面的测试似乎还是有问题。可以帮助我指出正确的方向。我还用一个哑组件编写了SearchBar。

// Searchbar.test.js
import React from 'react'
import { render, fireEvent } from '@testing-library/react';
import { SearchBar } from './SearchBar';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import getData from '../reducers';
import thunk from 'redux-thunk';

const store = createStore(
    getData,
    applyMiddleware(thunk)
);

const setup = () => {
    const utils = render(<Provider store={store}><SearchBar/></Provider>);
    const input = utils.getByLabelText('search-bar');
    return {
        input,
        ...utils
    }
}

test('It should keep a $ in front of the input', () => {
    const { input } = setup()
    fireEvent.change(input, { target: { value: 'search-bar-test' } })
    expect(input.value).toBe('search-bar-test')
})

// SearchBar.js
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import axios from 'axios';
import { generateSearchButtons } from '../actions/index';

export const SearchBar = () => {
    const dispatch = useDispatch();
    
    useEffect(() => {
        fetchSearchResults()
    })

    const getSearchValue = (e) => {
        const searchResult = e.target.value.toLowerCase();
        fetchSearchResults(searchResult);
    }

    const fetchSearchResults = (query) => {
        if(query == null) {
            query = "";
        }
        const searchUrl = `https://www.themealdb.com/api/json/v1/1/search.php?s=${query}`;

        axios.get(searchUrl)
        .then((res) => {
            dispatch(generateSearchButtons(res.data.meals))
        }).catch((err) => {
            console.log(err);
        })
    }
    
    return (
        <div>
            SearchBar
            <input aria-label="search-bar" type="text" onChange={(e) => getSearchValue(e)}/>
        </div>
    )
}

enter image description here

1 个答案:

答案 0 :(得分:0)

在主要组件文件(即SearchBar.js)中,您还具有测试代码。从下面将其删除。查看错误跟踪,发现render is not defined错误位于SearchBar.js中,而不是SearchBar.test.js