screen.getByText is not a function
Asked Answered
F

1

16

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"
  ]
}
Ferrotype answered 21/2, 2022 at 10:35 Comment(0)
A
19
import { screen, configure } from '@testing-library/react'

You need to import screen from RTL.

Allred answered 21/2, 2022 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.