How to test if dynamic text content is in the document using React-testing-library and Jest?

Viewed 1602

I'm trying to test a simple note-taking application using jest and react-testing-library. The first test, I'm trying to do is testing if the route displays the correct entry.

However an issue I've encountered is that, any value dynamically added to the dom using react hooks is inaccessible by react-testing-library. However static text works fine.

entry.test.js

import { render, screen, waitFor } from "@testing-library/react";
import { createMemoryHistory } from "history";
import { useState } from "react"
import { Route, Router } from "react-router-dom";
import Entry from "./entry";

describe("Entry",() => {
    it("should retrieve a single entry",async() => {

        const entries = [{
            title:"test1",
            desc:"I went to the beach",
            id:444
        },{
            title:'test2',
            desc:"This is test 2",
            id:695
        }]

        const history = createMemoryHistory();
        history.push('/entry/444');
        render(
            <Router history={history}>
                 <Route exact path='/entry/:id'>
                    <Entry entries={entries} />
                </Route>
            </Router>
        ,{route:'/entry/444'});
        
        screen.debug();
        const EntryTitle = screen.getByText('test1');
        await waitFor(() => screen.getByTestId('entry_title'));
         expect(screen.getByTestId('entry_title')).toHaveTextContent();
    })
})

entry.js

export default function Entry({entries,setEntry}) {
    const [isEditable,setEditable] = useState(false);
    const [entry,setCurrentEntry] = useState(null);
    const params = useParams();
    const history = useHistory();

    useEffect(() => {
        getEntry();
    }, [])

    const getEntry = () => {
        const current = entries.filter(entry => entry.id === params.id);
        setCurrentEntry(current[0]);
        return current[0];    
    }
     return (
       <h4 data-testid='entry_title' className="subtitle entry_title">{entry && entry.title}</h4> 
    )

error message

  TestingLibraryElementError: Unable to find an element with the text: test1. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

However using Screen.debug() returns:

  <h4 class="subtitle entry_title" data-testid="entry_title" />
0 Answers
Related