question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot getByRole for routerLink

See original GitHub issue

Background I’ve been trying to do a query by role to check a link on my page using: screen.getByRole('link', { name: /contact/i }). This keeps throwing an error as if the the element is undefined.

Debugging Inspecting my element shows it as

<a
  _ngcontent-oet-c21=""
  class="navigation--link navigation--link-active"
  href="/contact"
  ng-reflect-router-link="/contact"
  ng-reflect-router-link-active="navigation--link-active"
  routerlink="/contact"
  routerlinkactive="navigation--link-active"
>
  <i
    _ngcontent-oet-c21=""
    aria-hidden="true"
    class="far fa-clock navigation--icon"
  />
   contact
</a> 

I tried debugging while running tests by using queryAllByRole(component.fixture.nativeElement, 'navigation) to print out the DOM element and I see this. Looks like when the component is rendered it’s not adding in the href like it does for the live site

<a
  class="navigation--link"
  routerlink="/contact"
  routerlinkactive="navigation--link-active"
  >
    <i
      class="far fa-clock navigation--icon"
      />
  Contact
</a>

I had a similar issue trying to get an image by alt text using screen.getByRole('img', { name: /company logo/i }) but not sure what was stopping this as Angular isn’t adding the alt text.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
cjhavilandcommented, Sep 24, 2020

Hey, sorry this is a month later, but I just made some changes to my configuration and tests and it seems I either broke stuff, or just wasn’t testing if elements were in the Document in the first place… Pretty much any getByRole() isn’t working in my Angular project. I’ve tried using component.getRoleBy('...'), screen.getRoleBy('...'), findRoleBy() and none of them work, but the debugged html output looks good. If I try it in Testing Playground it works, just not in my project which makes me think it’s a configuration issue?

Error Example:

TestingLibraryElementError: Unable to find an accessible element with the role "table"

There are no accessible roles. But there might be some inaccessible roles. 
If you wish to access them, then set the `hidden` option to `true`. 
Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole

jest.config.js:

const { pathsToModuleNameMapper } = require('ts-jest/utils')
const { compilerOptions } = require('./tsconfig')

module.exports = {
  preset: 'jest-preset-angular',
  roots: ['<rootDir>/src/'],
  testMatch: ['**/+(*.)+(spec).+(ts)'],
  setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
  collectCoverage: true,
  coverageReporters: ['html'],
  coverageDirectory: 'coverage/qi-app',
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
    prefix: '<rootDir>/'
  })
}

setup-jest.ts:

import 'jest-preset-angular'
import '@testing-library/jest-dom'
import { configure } from '@testing-library/angular'
import { ReactiveFormsModule } from '@angular/forms'

/**
 * Configure Default Imports
 */
configure({
  defaultImports: [ReactiveFormsModule]
})

/**
 * Mocked Properties of the Global Window object
 */
const mock = () => {
  let storage: { [key: string]: string } = {}
  return {
    getItem: (key: string) => (key in storage ? storage[key] : null),
    setItem: (key: string, value: string) => (storage[key] = value ?? ''),
    removeItem: (key: string) => delete storage[key],
    clear: () => (storage = {})
  }
}

Object.defineProperty(window, 'localStorage', { value: mock() })
Object.defineProperty(window, 'sessionStorage', { value: mock() })

Object.defineProperty(window, 'CSS', { value: null })
Object.defineProperty(window, 'getComputedStyle', {
  value: () => {
    return {
      display: 'none',
      appearance: ['-webkit-appearance']
    }
  }
})

Object.defineProperty(document, 'doctype', {
  value: '<!DOCTYPE html>'
})

Object.defineProperty(document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true
    }
  }
})

/* output shorter and more meaningful Zone error stack traces */
Error.stackTraceLimit = 2

1reaction
yuriybelikecommented, Oct 17, 2021

In case someone comes across this, unable to find any element byRole.

This StackOverflow answer was what helped me.

The gist is to remove the “getComputedStyle” mock. (If you are using @angular-builders/jest it’s the globalMocks option).

Read more comments on GitHub >

github_iconTop Results From Across the Web

React Router - Testing Library
This example demonstrates React Router v6. For previous versions see below.
Read more >
How to test link using react-testing-library and jest
I'm trying to figure out how to test a link. I've been looking all over the place for a solution and I can't...
Read more >
testing-library - Bountysource
Cannot manually set route parameters on Vue-Testing-Library@next using ... const { getByRole } = render(h(App)); const button = getByRole("button"); ...
Read more >
Testing an NgRx project - Tim Deschryver
How write maintainable NgRx tests within an Angular application.
Read more >
react testing library click disabled button - You.com | The AI ...
TypeError: Cannot read property 'disabled' of null in react-testing-library ... getByRole("button", { name: /submit/i }); expect(emailErrorElement).not.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found