简体   繁体   中英

How to test the Swiper library with Jest in an Angular Nx repo?

I have an Nx repo with an Angular app and Jest as the test framework. The app has a component that uses the Swiper library. When trying to test the component, I get the following error messages:

  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    C:\Users\Philippe\Documents\Projects\temp\swiper-angular-nx-jest\node_modules\ssr-window\ssr-window.esm.js:148
    export { extend, getDocument, getWindow, ssrDocument, ssrWindow };
    ^^^^^^


      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.775 s
Ran all test suites.

 —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— 

 >  NX   Ran target test for project client (9s)

    ×    1/1 failed
    √    0/1 succeeded [0 read from cache]

PS C:\Users\Philippe\Documents\Projects\temp\swiper-angular-nx-jest> nx test

> nx run client:test

 FAIL   client  apps/client/src/app/carousel/carousel.component.spec.ts
  ● Test suite failed to run

    Cannot find module 'swiper_angular' from 'src/app/carousel/carousel.component.ts'

    Require stack:
      src/app/carousel/carousel.component.ts
      src/app/carousel/carousel.component.spec.ts

       5 | } from '@angular/core';
       6 | import SwiperCore, { Virtual } from 'swiper';
    >  7 | import { SwiperComponent, SwiperModule } from 'swiper/angular';
         | ^
       8 |
       9 | // install Swiper modules
      10 | SwiperCore.use([Virtual]);
      at Resolver.resolveModule (../../node_modules/jest-resolve/build/resolver.js:324:11)
      at Object.<anonymous> (src/app/carousel/carousel.component.ts:7:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        22.235 s
Ran all test suites.

 —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— 

 >  NX   Ran target test for project client (26s)

    ×    1/1 failed
    √    0/1 succeeded [0 read from cache]

PS C:\Users\Philippe\Documents\Projects\temp\swiper-angular-nx-jest> nx test

> nx run client:test

 FAIL   client  apps/client/src/app/carousel/carousel.component.spec.ts
  ● Test suite failed to run

    Cannot find module 'swiper_angular' from 'src/app/carousel/carousel.component.ts'

    Require stack:
      src/app/carousel/carousel.component.ts
      src/app/carousel/carousel.component.spec.ts

       5 | } from '@angular/core';
       6 | import SwiperCore, { Virtual } from 'swiper';
    >  7 | import { SwiperComponent, SwiperModule } from 'swiper/angular';
         | ^
       8 |
       9 | // install Swiper modules
      10 | SwiperCore.use([Virtual]);

      at Resolver.resolveModule (../../node_modules/jest-resolve/build/resolver.js:324:11)
      at Object.<anonymous> (src/app/carousel/carousel.component.ts:7:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.117 s
Ran all test suites.

 ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

 >  NX   Ran target test for project client (8s)

    ×    1/1 failed
    √    0/1 succeeded [0 read from cache]

I have tried the following ideas, with no luck:

Here is my jest.config.ts:

module.exports = {
  displayName: 'client',
  preset: '../../jest.preset.ts',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.(html|svg)$',
    },
  },
  coverageDirectory: '../../coverage/apps/client',
  transform: {
    '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
  },
  transformIgnorePatterns: [`<rootDir>/node_modules/(?!.*\\.mjs$|swiper)`],
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ],
};

Here is the component:

import { CommonModule } from '@angular/common';
import {
  ChangeDetectionStrategy, Component, NgModule,
  ViewChild
} from '@angular/core';
import SwiperCore, { Virtual } from 'swiper';
import { SwiperComponent, SwiperModule } from 'swiper/angular';

// install Swiper modules
SwiperCore.use([Virtual]);

@Component({
  selector: 'swiper-angular-nx-jest-carousel',
  template: `
    <swiper #swiper [virtual]="true">
      <ng-template swiperSlide>Slide 1</ng-template>
      <ng-template swiperSlide>Slide 2</ng-template>
      <ng-template swiperSlide>Slide 3</ng-template>
      <ng-template swiperSlide>Slide 4</ng-template>
      <ng-template swiperSlide>Slide 5</ng-template>
      <ng-template swiperSlide>Slide 6</ng-template>
      <ng-template swiperSlide>Slide 7</ng-template>
    </swiper>
    <button (click)="slidePrev()">Prev slide</button>
    <button (click)="slideNext()">Next slide</button>
  `,
  styleUrls: ['./carousel.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CarouselComponent {
   @ViewChild('swiper', { static: false }) swiper!: SwiperComponent;
  slideNext(){
    this.swiper.swiperRef.slideNext(100);
  }
  slidePrev(){
    this.swiper.swiperRef.slidePrev(100);
  }
}

@NgModule({
  imports: [CommonModule, SwiperModule],
  declarations: [CarouselComponent],
  exports: [CarouselComponent],
})
export class CarouselComponentModule {}

And the test file:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CarouselComponent, CarouselComponentModule } from './carousel.component';


describe('CarouselComponent', () => {
  let component: CarouselComponent;
  let fixture: ComponentFixture<CarouselComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [CarouselComponentModule],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(CarouselComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

I have reproduced the problem in a small repo which you can find here: https://github.com/snowfrogdev/swiper-angular-nx-jest

  1. in jest.config.ts there is no need to mention swiper library, leave the default value for transformIgnorePatterns :

transformIgnorePatterns: [`<rootDir>/node_modules/(?!.*\\.mjs$)`],

  1. extract your CarouselComponentModule into a separate file if you really want to keep it away from app.module.ts : I created apps/client/src/app/carousel/carousel-component.module.ts with content
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { SwiperModule } from 'swiper/angular';
import { CarouselComponent } from './carousel.component';

@NgModule({
  imports: [CommonModule, SwiperModule],
  declarations: [CarouselComponent],
  exports: [CarouselComponent],
})
export class CarouselComponentModule {}
  1. update the import in app.module.ts

  2. clean up your component file carousel.component.ts

import { ChangeDetectionStrategy, Component, ViewChild } from '@angular/core';
import SwiperCore, { Virtual } from 'swiper';
import { SwiperComponent } from 'swiper/angular';

// install Swiper modules
SwiperCore.use([Virtual]);

@Component({
  selector: 'swiper-angular-nx-jest-carousel',
  template: `
    <swiper #swiper [virtual]="true">
      <ng-template swiperSlide>Slide 1</ng-template>
      <ng-template swiperSlide>Slide 2</ng-template>
      <ng-template swiperSlide>Slide 3</ng-template>
      <ng-template swiperSlide>Slide 4</ng-template>
      <ng-template swiperSlide>Slide 5</ng-template>
      <ng-template swiperSlide>Slide 6</ng-template>
      <ng-template swiperSlide>Slide 7</ng-template>
    </swiper>
    <button (click)="slidePrev()">Prev slide</button>
    <button (click)="slideNext()">Next slide</button>
  `,
  styleUrls: ['./carousel.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CarouselComponent {
  @ViewChild('swiper', { static: false }) swiper!: SwiperComponent;
  slideNext() {
    this.swiper.swiperRef.slideNext(100);
  }
  slidePrev() {
    this.swiper.swiperRef.slidePrev(100);
  }
}
  1. add into apps/client/tsconfig.spec.json the path to swiper_angular into compilerOptions
"paths": {
      "swiper_angular": ["node_modules/swiper/angular"]
  1. Finally, your test would be like this
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { CarouselComponent } from './carousel.component';

describe('CarouselComponent', () => {
  let component: CarouselComponent;
  let fixture: ComponentFixture<CarouselComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [CarouselComponent],
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(CarouselComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

However, it still does not work due to

Cannot read property 'ɵcmp' of undefined

error

After adding swiper|ssr-window|dom7 to jest.config.js it works.

Should look like this:

transformIgnorePatterns: [
    'node_modules/(?!.*\\.mjs$|swiper|ssr-window|dom7)',
],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM