Ionic 4: Creating mock storage

后端 未结 3 1204
忘掉有多难
忘掉有多难 2021-01-12 07:28

I am trying to use Testbed in a new Angular 7 / Ionic 4 app but cannot run any tests because my components depend on an Ionic native plugin, storage.

app.com

3条回答
  •  星月不相逢
    2021-01-12 07:45

    As others wrote, Storage works in browsers, so I did not need mocking it for testing. This worked for me (StorageWrapperService is my service which depends on Ionic's Storage):

    import { TestBed } from '@angular/core/testing';
    
    import { StorageWrapperService } from './storage-wrapper.service';
    import { IonicStorageModule, Storage } from '@ionic/storage';
    
    describe('StorageWrapperService', () => {
      let service: StorageWrapperService;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [
            IonicStorageModule.forRoot({
              name: '__mydb',
              driverOrder: ['localstorage']
            })
          ],
        });
        service = TestBed.inject(StorageWrapperService);
      });
    
      it('should be created', () => {
        expect(service).toBeTruthy();
      });
    
    });
    

    Additional info:

    localstorage will not be cleared between tests, so probably you want to use something like this:

    describe('StorageWrapperService', () => {
      let service: StorageWrapperService;
      let storage: Storage;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [
            IonicStorageModule.forRoot({
              name: '__mydb',
              driverOrder: ['localstorage']
            })
          ]
        });
        service = TestBed.inject(StorageWrapperService);
        storage = TestBed.inject(Storage);
      });
    
    ...
    });
    

    And clear storage at the end of every tests:

      it('...', (done) => {
          storage.clear().then(() => done());
      });
    

提交回复
热议问题