简体   繁体   English

如何在 Angular Nx 存储库中使用 Jest 测试 Swiper 库?

[英]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.我有一个带有 Angular 应用程序和 Jest 作为测试框架的 Nx 存储库。 The app has a component that uses the Swiper library.该应用程序有一个使用Swiper库的组件。 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:这是我的 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我在一个小仓库中重现了这个问题,你可以在这里找到它: 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 :jest.config.ts中无需提及swiper库,保留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如果您真的想让CarouselComponentModule远离app.module.ts ,请将其提取到一个单独的文件中:我创建了带有内容apps/client/src/app/carousel/carousel-component.module.ts
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更新app.module.ts中的导入

  2. clean up your component file carousel.component.ts清理你的组件文件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将 swiper_angular 的路径添加到apps/client/tsconfig.spec.json swiper_angular 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.swiper|ssr-window|dom7jest.config.js后,它就可以工作了。

Should look like this:应该是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular NgRx 集成测试不起作用(使用 Nx 和 Jest) - Angular NgRx integration test not working (with Nx and Jest) Nx、Angular、Jest 和声纳 - Nx, Angular, Jest and Sonar Angular NX/Jest 测试一个指令并通过不同测试用户 - Angular NX/Jest testing of a directive and passing different test Users 使用玩笑来测试 Angular 库? - Using jest to test an Angular Library? 将 Swiper 6 升级到 7 后,在单元测试(开玩笑)上找不到模块 'swiper_angular' - Cannot find module 'swiper_angular' on unit test (jest) after upgrading Swiper 6 to 7 如何让 Jest 正确转换 node_modules/@nativescript/core? 开玩笑 + NativeScript + Angular + Nx - How can I get Jest to transpile node_modules/@nativescript/core properly? Jest + NativeScript + Angular + Nx 发布现有的 NX 角度库 - publish an existing NX angular library 如何用笑话和黄瓜测试 Angular 6? - How to test Angular 6 with jest and cucumber? 如何从库中导入组件(在Angular中为nrwl / nx) - How to import a component from a library (in nrwl/nx with Angular) @nrwl/nx angular 在单个测试运行中运行所有覆盖测试,以在我的 mono 存储库中获取所有覆盖代码 - @nrwl/nx angular Run all test for coverage in a single test run to get all covered code in my mono repo
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM