Ionic 4: Creating mock storage
Asked Answered
N

3

8

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.component.spec.ts

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {TestBed, async, fakeAsync, tick} from '@angular/core/testing';

import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import {RouterTestingModule} from '@angular/router/testing';
import {Router} from '@angular/router';
import {Location} from '@angular/common'

import { LoginPage } from './pages/login/login.page';
import { routes } from "./app-routing.module";
import {HttpClientTestingModule} from '@angular/common/http/testing';
import {StorageMock} from './testing/mocks/storage.mock';
import {IonicStorageModule} from '@ionic/storage';

describe('AppComponent', () => {

  let statusBarSpy, splashScreenSpy, platformReadySpy, platformSpy, storageSpy;
  let router: Router;
  let location: Location;
  let fixture;
  let comp: AppComponent;

  beforeEach(async(() => {
    statusBarSpy = jasmine.createSpyObj('StatusBar', ['styleDefault']);
    splashScreenSpy = jasmine.createSpyObj('SplashScreen', ['hide']);
    platformReadySpy = Promise.resolve();
    platformSpy = jasmine.createSpyObj('Platform', { ready: platformReadySpy });
    storageSpy = jasmine.createSpyObj('Storage', ['get', 'set', 'clear', 'remove', 'ready']);

    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [
        RouterTestingModule.withRoutes(routes),
        IonicStorageModule.forRoot(),
        HttpClientTestingModule,
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        { provide: StatusBar, useValue: statusBarSpy },
        { provide: SplashScreen, useValue: splashScreenSpy },
        { provide: Platform, useValue: platformSpy },
        { provide: Storage, useClass: StorageMock }
      ],
    }).compileComponents();

    router = TestBed.get(Router);
    location = TestBed.get(Location);
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance;
    router.initialNavigation();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });

  it('should initialize the app', async () => {
    TestBed.createComponent(AppComponent);
    expect(platformSpy.ready).toHaveBeenCalled();
    await platformReadySpy;
    expect(statusBarSpy.styleDefault).toHaveBeenCalled();
    expect(splashScreenSpy.hide).toHaveBeenCalled();
  });

  it('navigates to "" redirects you to /login', fakeAsync(() => {
    router.navigate(['']);
    tick();
    expect(location.path()).toBe('/login')
  }));

  afterEach(() => {
    fixture.destroy();
    comp = null
  })
});

And have created my own StorageMock:

import {Storage, StorageConfig} from '@ionic/storage';

export class StorageMock extends Storage {
  driver: string;
  vals: {};

  constructor(config: StorageConfig) {
    super({})
  }

  clear() {
    return new Promise<void>((res) => res())
  }

  ready() {
    return new Promise<LocalForage>((res) => res())
  }

  get(key: string) {
    return new Promise((res) => res(this.vals[key]))
  }

  set(key, val) {
    return new Promise((res) => {
      this.vals[key] = val;
      res()
    })
  }

  remove(key) {
    return new Promise((res) => {
      delete this.vals[key];
      res()
    })
  }
}

However when I run my test, I still see:

Error: Can't resolve all parameters for Storage: (?).

What am I missing?

Naman answered 23/4, 2019 at 14:47 Comment(1)
use local storage it will workSouthern
A
9

First, import Storage:

import { Storage } from '@ionic/storage';

Create a const for mock:

 const storageIonicMock: any = {
     get: () => new Promise<any>((resolve, reject) => resolve('As2342fAfgsdr')),
     set: () => ...
    };

Configure your TesBed

TestBed.configureTestingModule({
      imports: [],
      providers: [
        {
          provide: Storage,
          useValue: storageIonicMock
        }
      ]
    });
Around answered 13/6, 2019 at 8:49 Comment(0)
D
2

The Ionic plugin storage also works in a browser environment.

You don't need to create a mock and you can directly import, define and inject it in your component (if you are running your test in a browser environment) :

First import :

import { Storage } from '@ionic/storage';
import { MyComponent } from './my-component';

Declare a global component variable :

let component: MyComponent;

Then and for each test, define and inject the storage in your component :

beforeEach(() => {
    const storage = new Storage({         // Define Storage
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql']
    });
    component = new MyComponent(storage); // Inject Storage in your component
  }
Diligent answered 23/6, 2019 at 1:37 Comment(0)
E
0

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());
  });
Extravasate answered 26/9, 2020 at 7:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.