[英]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
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$)`],
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 {}
update the import in app.module.ts
更新app.module.ts
中的导入
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);
}
}
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"]
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|dom7
到jest.config.js
后,它就可以工作了。
Should look like this:应该是这样的:
transformIgnorePatterns: [
'node_modules/(?!.*\\.mjs$|swiper|ssr-window|dom7)',
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.