Search code examples
jestjsionic5ts-jestangular11

Jest testing with angular ionic storage is failing


Hi i am using angular 11 and ionic 5 ;

for ionic storage i am using @ionic/storage-angular:^3.0.6 module.

during jest unit tests i am getting

Cannot find module '@ionic/storage' from 'node_modules/@ionic/storage-angular/bundles/ionic-storage-angular.umd.js'

@ionic/storage-angular is a dependency in one of the service which i mocked

jest.confi.js has

transformIgnorePatterns: [
    './node_modules/(?!@ionic|ngx-socket-io/|!@ionic/storage-angular)'
]

spec file mocking the service

let storeServiceStub={
  get:jest.fn().mockResolvedValue({})
};

await TestBed.configureTestingModule({
      declarations: [ DataSyncComponent ],
      providers:[
        { provide: StoreService, useValue: storeServiceStub },
      ]
})
.compileComponents();

@ionic/storage-angular is a of store service which i m replacing with stub;

testing env to repo bug package.json

dependencies:{
  ...
  "@ionic/storage-angular": "^3.0.6",
  ...
}
devDependencies:{
  ...
  "jest": "^27.0.3",
  "jest-preset-angular": "^9.0.1",
  "@types/jest": "^26.0.23",
  ...

}

node v 14 os osx 11.2.2


Solution

  • I can fix it by adding the following configuration in my jest.config.js

    moduleNameMapper: {
            '^@ionic/storage': '<rootDir>/node_modules/@ionic/storage/dist/esm/index.d.ts',
        }, 
    

    Quite similar to the answer from @Ferraria. But the module name starts with the character ^ and the path ends in index.d.ts.

    My complete configuration is

    module.exports = {
        "preset": "jest-preset-angular",
        "setupFilesAfterEnv": ["<rootDir>/setup-jest.ts"],
        "transformIgnorePatterns": [
            "node_modules/(?!@ngrx|@ionic-native|@ionic)"
        ],
        moduleNameMapper: {
            '^@ionic/storage': '<rootDir>/node_modules/@ionic/storage/dist/esm/index.d.ts',
        },
        setupFiles: ["jest-canvas-mock"]
    };