screen.getByText 不是函数

screen.getByText is not a function

在我开始转向 screen > getByText/etc 测试方式之前,我大部分时间都在使用 jest 和 react-testing-library 没有问题。

测试

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')
  })
})

失败

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"
  ]
}
import { screen, configure } from '@testing-library/react'

您需要从 RTL 导入 screen