将 Swiper 6 升级到 7 后无法在单元测试(开玩笑)中找到模块 'swiper_angular'

Cannot find module 'swiper_angular' on unit test (jest) after upgrading Swiper 6 to 7

我 运行 在 upgrading Swiper 6 to 7 之后的单元测试中遇到了问题。我正在使用 Angular 12 和 Swiper 7.3.1。在升级之前,单元测试工作正常(Swiper 版本 6.5.9)。

我在这样的测试中使用 SwiperModule

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { of } from 'rxjs';
import { SwiperComponent, SwiperModule } from 'swiper/angular';

import { TeaserWrapperContainerComponent } from './teaser-wrapper-container.component';
import { InterfaceState } from '@migrosonline/shared-deps-all/core/interface/interface.store';


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

const mockedSwiperComponent = {
        swiperRef: {
            slideNext: jest.fn(),
            slidePrev: jest.fn(),
            destroy: jest.fn(),
            update: jest.fn()
        }
    } as unknown as SwiperComponent;

beforeEach(
        waitForAsync(() => {
            mockedInterfaceService.prototype.select = jest.fn();

            TestBed.configureTestingModule({
                declarations: [TeaserWrapperContainerComponent],
                imports: [SwiperModule],
                providers: [{ provide: InterfaceService, useClass: mockedInterfaceService }],
                schemas: [CUSTOM_ELEMENTS_SCHEMA]
            }).compileComponents();
        })
    );

    beforeEach(() => {
        fixture = TestBed.createComponent(TeaserWrapperContainerComponent);
        component = fixture.componentInstance;
        component.teaserGroupSliderRef = mockedSwiperComponent;
    });

    it('should create', () => {
        fixture.detectChanges();

        expect(component).toBeTruthy();
    });

});

我得到的错误是:

Cannot find module 'swiper_angular' from 'src/lib/shared/teaser/teaser-wrapper-container/teaser-wrapper-container.component.spec.ts'

      3 | import { of } from 'rxjs';
    > 4 | import { SwiperComponent, SwiperModule } from 'swiper/angular';

我将不胜感激 ideas/comments/suggestions。

以防其他人 运行 遇到此问题,问题与测试的 eslinttslint 配置有关,并已修复添加 swiper_angulartsconfig.json(或 tsconfig.spec.json)文件中的 compilerOptions > 路径:

"compilerOptions": {
    ...
    "paths": {
      "swiper_angular": ["node_modules/swiper/angular"]
    } 
  }

我在 Swiper 问题中找到了解决方案:https://github.com/nolimits4web/swiper/issues/4315

如果您在导入模块时遇到问题,只需在测试顶部以这种方式模拟它:

jest.mock('swiper/angular', () => ({
    SwiperModule: jest.fn(),
}));

https://jestjs.io/docs/mock-functions#mocking-modules

如果您需要声明 SwiperComponent,只需在测试顶部模拟它即可:

@Component({
    selector: 'swiper',
    template: '',
})
export class SwiperMockComponent {
    @Input() pagination = false; // if pagination is needed
}

并在 TestBed 或 MockBuilder 中声明:

TestBed.configureTestingModule({
    declarations: [SomeComponent, SwiperMockComponent],
    ...
});