0
votes

As a noob I am completely stuck with testing in Jest. Why the terminal is showing referenceErrror, render is not defined. Even when I imported that from @testing-library/react it seems that there is something wrong with my test below. Could some help me pointing to the right direction. I also wrote the SearchBar in a dumb component.

// 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

1 Answers

0
votes

In your main component file i.e. SearchBar.js you have testing code as well. Remove that from below. See the error trace, the render is not defined error is in SearchBar.js and not in SearchBar.test.js