DEV Community

Cover image for How to use testing-library in Angular 15
Michael Vogt
Michael Vogt

Posted on • Edited on

4

How to use testing-library in Angular 15

The included karma/jasmine tests do not follow modern testing-principles like role selectors.

Therefore I recommend removing these tests and replace them with the more useful testing-library approach.

Steps to setup testing-library in an Angular 15 project

Remove the karma/jasmine tests

  • remove all karma & jasmine dependencies from the package.json
npm remove -D @types/jasmine jasmine-core karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter
Enter fullscreen mode Exit fullscreen mode

Install testing-library

npm i -D @testing-library/dom @testing-library/angular
Enter fullscreen mode Exit fullscreen mode

Install jest test runner

We use jest-preset-angular build on top of ts-jest.

 npm i -D jest @types/jest jest-preset-angular
Enter fullscreen mode Exit fullscreen mode

Create jest configuration file in root: jest.config.js

module.exports = {
  preset: "jest-preset-angular",
  setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"]
};

Enter fullscreen mode Exit fullscreen mode

create setup-jest.ts, also includes the most important mocks...

import 'jest-preset-angular/setup-jest';
Object.defineProperty(window, 'CSS', { value: null });
Object.defineProperty(document, 'doctype', {
  value: '<!DOCTYPE html>',
});
Object.defineProperty(window, 'getComputedStyle', {
  value: () => {
    return {
      display: 'none',
      appearance: ['-webkit-appearance'],
    };
  },
});
/**
 * ISSUE: https://github.com/angular/material2/issues/7101
 * Workaround for JSDOM missing transform property
 */
Object.defineProperty(document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});


Enter fullscreen mode Exit fullscreen mode

change test script

Inside the package.json just replace the test script

from

  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
Enter fullscreen mode Exit fullscreen mode

to

  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "jest --watch"
  },
Enter fullscreen mode Exit fullscreen mode

and remove the test settings from angular.json

...
      "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
...
Enter fullscreen mode Exit fullscreen mode

create a single angular module definition

I always have a single angular module definition I can pass to testing-library/angular render method. I just reuse it all the time


export const testModule = {
  declarations: [
    // ...all the declarations from the app.module.ts
  ],
  imports: [
    // ...all the imports from the app.module.ts
    BrowserModule,
    AppRoutingModule,
    CommonModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
};

Enter fullscreen mode Exit fullscreen mode

enjoy

npm run test

should just run the tests inside jest. The existing tests in spec file should be replace by testing-library style tests.

example test:

import { screen, render } from '@testing-library/angular';
import { testModule } from '../../test.module';

import { CreateAppointmentPageComponent } from './create-appointment-page.component';

describe('CreateAppointmentPageComponent', () => {
  it('should create', async () => {
    await render(CreateAppointmentPageComponent, testModule);
    screen.logTestingPlaygroundURL();
  });
});


Enter fullscreen mode Exit fullscreen mode

known issues

import from src folder does not work, it just does not find something under e.g.

import { TestService } from 'src/app/services/testService.ts'
Enter fullscreen mode Exit fullscreen mode

instead I try always to use relative imports, I never had trouble using them...

import { TestService } from '../../services/testService.ts'
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️