Skip to content

React lazy load component not able to find the text in props #920

@brendonco

Description

@brendonco

https://codesandbox.io/s/react-lazy-component-testing-forked-gyc2q?file=/src/LazyComponent.test.js

LazyComponent.js

import React from "react"

export default ({ title, count }) => (
  <div>
    <h1>`${title} (${count})`</h1>
    <p>
      This component is Lazy and will be imported after 1000ms, you should be
      able to see "Loading". Reload if you didn't
    </p>
  </div>
)

If I used variable to assert the text, the test will failed. If I change the variable to the exact text assigned to the variable, it works. any reason why?

LazyComponent.test.js

import React, { lazy, Suspense } from "react"
import { render, screen } from "@testing-library/react"
// For codeSandbox
import "@testing-library/jest-dom/extend-expect"

const LazyComponent = lazy(() => import("./LazyComponent"))

test("renders lazy component", async () => {
  // Will render the lazy component
  const title = "I'm so lazy";
  const count = 1;
  render(
    <Suspense fallback={<p>Loading...</p>}>
      <LazyComponent title={title} count={count}/>
    </Suspense>
  )
  // Match text inside it
  const textToMatch = await screen.findByText(title)
  expect(textToMatch).toBeInTheDocument()
})

Here's a sample code to test.
https://codesandbox.io/s/react-lazy-component-testing-forked-gyc2q?file=/src/LazyComponent.js:0-265

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions