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



我有一个Nx存储库,其中包含Angular应用程序和Jest作为测试框架。该应用程序具有使用滑动器库的组件。尝试测试组件时,我收到以下错误消息:

● 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:UsersPhilippeDocumentsProjectstempswiper-angular-nx-jestnode_modulesssr-windowssr-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:UsersPhilippeDocumentsProjectstempswiper-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:UsersPhilippeDocumentsProjectstempswiper-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]

我尝试了以下想法,但没有运气:

  • Angular v13 Jest with nx test - 语法错误:无法在运行时使用模块外部的导入语句。
  • https://github.com/nrwl/nx/issues/7170
  • https://github.com/nrwl/nx/issues/7844

这是我的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',
],
};

这是组件:

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 {}

和测试文件:

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();
});
});

我已经在一个小的存储库中重现了这个问题,你可以在这里找到:https://github.com/snowfrogdev/swiper-angular-nx-jest

  1. jest.config.ts中无需提及swiper库,将默认值保留为transformIgnorePatterns

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

    如果您
  1. 真的想让您的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. 更新导入app.module.ts

  2. 清理组件文件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. 添加到apps/client/tsconfig.spec.json路径以swiper_angularcompilerOptions
"paths": {
"swiper_angular": ["node_modules/swiper/angular"]
  1. 最后,你的测试是这样的
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();
});
});

但是,由于

Cannot read property 'ɵcmp' of undefined

错误

swiper|ssr-window|dom7添加到jest.config.js后,它可以工作。

应如下所示:

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

最新更新