The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method.

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"
  ]
}

Answer №1

import { getScreen, setup } from '@testing-library/react'

In order to utilize getScreen, you must import it from RTL.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Techniques for adding values to arrays in JavaScript

My Anticipated Result let Album = { album_desc: AlbumTitle, id: 1, album_title: 'ss', AlbumDescription: 'sdsd', ImageName: 'image.jpg', album_pics: below array }; I am looking to dynamically p ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

View Preview Image using the following image tag in JavaScript

I am trying to display an image preview using the img tag that is placed after my input field. Here is my HTML: <input name="image" type="file" id="uploadImage" onchange="PreviewImage(this);" /> ...

Outputting data to a WriteStream within an Event Listener

My current issue involves an EventEmitter object set up to listen for events and write information to a file when the event is emitted. Using fs.createWriteStream(path, { flags: 'a'});, I have opened a FileStream. However, emitting events quickly ...

What are the guidelines for utilizing square brackets [ ] in directives like @Inputs?

I'm feeling a bit lost. Check out this straightforward directive: @Directive({ selector: '[myDirective]' }) export class MyDirective { private textContent: string; private isEnabled: boolean; @Input() myD ...

How can we include identical item names within a single JavaScript object?

My attempt at achieving the desired result involves creating an object like this: var obj = {id: id, items: "asdf", items: "sdff", test: varTest}; However, I face a challenge where I need to dynamically add two elements with the same name 'items&apo ...

Transferring a JavaScript variable to PHP using Ajax within the same webpage

Check out my HTML and JavaScript code: <form id="form" action="javascript:void(0)"> <input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font- ...

What is the best approach for scaling @material-ui Skeleton in a grid row with variable heights?

I am working on creating a grid of Avatar images with a transition state where I want to show a skeleton representation of the image. To achieve this, I am using @material-ui/lab/Skeleton. The issue I'm facing is that since my images are set to autos ...

Receiving the outcome of an asynchronous function in JavaScript

async function retrieveKey() { try { var key = await dec.awsDecrypt('dev-frontend') return key; } catch(err) { } } //calling the function const result = retrieveKey() In the code snippet above, there is an asynchronous ...

Animating the smooth collapse of panels within listviews

I have successfully implemented a smooth animation code for a collapsible panel, and it is working wonderfully: <script type="text/javascript"> function pageLoad(sender, args) { smoothAnimation(); } function smoothAnimation() ...

Error: Chrome is reporting an "Unexpected token :" while Firefox is showing a "SyntaxError: missing ; before statement" issue

Here's the code snippet in question: function getCategoryResponse() { var appid = "1"; $.ajax({ type: 'GET', url: 'http://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/genres?id=36&callback=myCallbackFu ...

Manually validate inputs in Angular

I've encountered an issue with the bootstrap datepicker. When I click on the date icon, the date and time automatically populate in the input field. However, the input remains invalid because I haven't directly interacted with it. Has anyone else ...

I'm struggling with my project called "Number TSP" and I can't seem to figure out why it's not working properly

Upon reaching the end of my code, I am encountering an issue where instead of seeing the expected output of "Done!", it displays undefined. This is the code in question: const container = document.querySelector(".container") const table = document.querySe ...

A guide on passing variables to the MUI styled function within ReactJS

Is it possible to pass a variable directly to the styled function in order to conditionally change style properties while using MUI styled function? I want to achieve something like this: borderColor: darkMode ? 'white' : 'black' const ...

Encountering an unexpected token error in Vercel during deployment, even though the code runs smoothly in the

I'm facing an issue with a SyntaxError: Unexpected token '??='. I am not sure how to resolve it, so any help would be greatly appreciated. Thank you in advance. SyntaxError: Unexpected token '??=' at wrapSafe (internal/modules ...

tsc does not support the use of the '--init' command option

Encountering an error when running npx tsc --init: $ npx tsc --init npx: installed 1 in 1.467s error TS5023: Unknown compiler option 'init'. I've added the typescript package using Yarn 2: $ yarn add -D typescript ➤ YN0000: ┌ Resolution ...

I'm facing a challenge where Multer is preventing me from showing images in my React app

Hi there, I'm currently facing an issue where I am using multer to save files on my server and store their path in mongodb. However, I am struggling to display them on my React application. Any assistance would be greatly appreciated. Thank you in ad ...

Is there a way to access and read an Excel file stored within the assets folder using Angular?

I need assistance converting an excel file to a JSON format. My excel file is currently stored in the assets folder, and I am looking for guidance on how to access it from app.component.ts. Any help would be greatly appreciated! ...

Unable to run the JSON.parse() function while using the 1.10.2 version of jquery.min.js

Has anyone else encountered a situation where using JSON.parse() to parse the PHP array return only works when applying 1.3.2/jquery.min.js and not 1.10.2/jquery.min.js? If so, what solution did you find? PHP array return $returnArray['vercode' ...

Guide on setting up ShareThis on a Vue.js project

I attempted to include this code in the public index.html file: <script type='text/javascript' src='https://platform-api.sharethis.com/js/sharethis.js#property=5f4e15b2e56e550012ae1e77&product=inline-share-buttons' async='a ...