Home > OS >  screen.getByText is not a function
screen.getByText is not a function

Time:02-21

I am using jest with react-testing-library for the most part without issues until I started to move to the screen > getByText/etc way of testing.

Test

describe('test the dashboard when loaded', () => {
  it('is not loading', async () => {
    render(<ComponentToTest />)
    expect(screen.getByText(/loading/i)).not.toBeInTheDocument()
  })

  it('displays the case summary correctly', async () => {
    const allCasesElement = getByTestId(/Timeline/i)
    within(allCasesElement).findByText('30/12/2021')
    within(allCasesElement).findByText('12:06')
    within(allCasesElement).findByText('enums.case.VERIFICATION_GO_TO_COMPLETION')
  })
})

Failure

TS2339: Property 'getByText' does not exist on type 'Screen'.

screen.getByText is not a function
TypeError: screen.getByText is not a function
    at Object.<anonymous> (/var/www/src/pages/Application/Overview/Timeline/Timeline.test.tsx:250:19)
    at Promise.then.completed (/var/www/node_modules/jest-circus/build/utils.js:276:28)
    at new Promise (<anonymous>)

setupTests.ts

import '@testing-library/jest-dom'
import '@testing-library/jest-dom/extend-expect'
import { configure } from '@testing-library/react'

configure({ testIdAttribute: 'data-name' })
window.__ENV__ = {}

ts-config

{
  "compilerOptions": {
    "baseUrl": "src",
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "rootDirs": [
      "src",
      "stories",
      "config"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "noImplicitAny": false
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "docs"
  ],
  "setupFilesAfterEnv": [
    "<rootDir>/src/setupTests.js"
  ]
}

CodePudding user response:

import { screen, configure } from '@testing-library/react'

You need to import screen from RTL.

CodePudding user response:

I've only started with testing-library myself, but I believe you need to use the object returned by render:

const component = render(<ComponentToTest />)
expect(component.getByText(/loading/i)).not.toBeInTheDocument()
  • Related