Open adammendoza opened 6 years ago
Even I am getting the same error. Can anyone please tell how to solve this issue??
Ok. I'm sure you already have solved the problem but here are some solutions:
add the LocalStorageModule
to the imports list of your test module configuration
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
// other imports...
LocalStorageModule.forRoot()
],
// declarations, providers etc...
})
}));
OR provide a simple mock object that contains all functions that are used in your service (e.g. set
and get
). When you want to return another value than null in a test case simply use returnValue
, returnValues
, callFake
or callThrough
for your Spy.
let localStorageMock: Partial<LocalStorageService>;
beforeEach(() => {
localStorageMock = {
get: jasmine.createSpy('get').and.returnValue(null)
set: jasmine.createSpy('set')
}
});
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
{ provide: LocalStorageService, useValue: localStorageMock }
],
// declarations, imports etc...
})
}));
OR create a class, that defines a Mock for the LocalStorageService once for your project. This class has to contain all public functions of the LocalStorageService. Make sure that the class will be excluded when you create the app bundle for production.
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
{ provide: LocalStorageService, useClass: LocalStorageServiceMock }
],
// declarations, imports etc...
})
}));
When you use your AuthenticationService
in another service or component make sure that you have created a mock for the LocalStorageService
as well because you have a dependency in your service to the LocalStorageService. Another way is to create a mock class for your AuthenticationService
that has no dependencies to other services.
It is very simple, like if you are using the service in HomePage, so go to HomePage -> home.page.spec.ts then
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { HomePage } from './home.page';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
describe('HomePage', () => {
let component: HomePage;
let fixture: ComponentFixture<HomePage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ HomePage ],
imports: [IonicModule.forRoot()],
providers: [LocalStorageService]
}).compileComponents();
fixture = TestBed.createComponent(HomePage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
Just add providers , add provider name and your test will run.
I'm getting this error when running ng test