'Cannot find module 'swiper_angular' on unit test (jest) after upgrading Swiper 6 to 7
I'm running into a problem on my unit tests after upgrading Swiper 6 to 7. I'm using Angular 12 and Swiper 7.3.1. Before upgrading it the unit tests were working fine (Swiper version 6.5.9).
I'm using the SwiperModule in my tests like this:
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();
});
});
and the error I get is this:
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';
I would appreciate any ideas/comments/suggestions.
Solution 1:[1]
If you have trouble to import a module, just mock it in this way at the top of your test:
jest.mock('swiper/angular', () => ({
SwiperModule: jest.fn(),
}));
https://jestjs.io/docs/mock-functions#mocking-modules
If you need to declare the SwiperComponent, just mock it at the top of your test:
@Component({
selector: 'swiper',
template: '',
})
export class SwiperMockComponent {
@Input() pagination = false; // if pagination is needed
}
And declare it in TestBed or MockBuilder:
TestBed.configureTestingModule({
declarations: [SomeComponent, SwiperMockComponent],
...
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hmartini |
