Struggling with accessing mocked service methods in Angular 2 during component unit testing. Seeking guidance on a standard approach, despite following Angular docs closely. The challenge lies in reaching the mocked service's methods.
My immediate goal is to grant the component access to the mocked service's API and specifically spy on the login method to verify its invocation.
login.page.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { DBService } from '../../services/db/db.service';
import { TabsPage } from '../tabs/tabs.page';
@Component({
templateUrl: 'login.page.html',
})
export class LoginPage {
constructor(public navCtrl: NavController, public dbService: DBService) {}
login() {
this.dbService.login();
}
}
db.service.mock.ts
export class MockDBService {
public login(): string {
return 'login service';
}
}
login.page.spec.ts
import { LoginPage } from './login.page';
import { TestBed, inject, ComponentFixture } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { NavController } from 'ionic-angular';
import { mockNavController } from 'ionic-angular/util/mock-providers';
import { DBService } from '../../services/db/db.service';
import { MockDBService } from '../../services/db/db.service.mock';
describe('Login Page:', () => {
let fixture: ComponentFixture<LoginPage>;
let component: LoginPage;
let mockDBServiceInstance: MockDBService;
beforeEach(() => {
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
declarations: [
LoginPage,
],
providers: [
{provide: NavController, useValue: mockNavController},
{provide: DBService, useValue: MockDBService},
LoginPage,
],
});
fixture = TestBed.createComponent(LoginPage);
component = fixture.componentInstance;
mockDBServiceInstance = TestBed.get(DBService);
});
describe('testing the login functionality', () => {
it('should call the login method on the DBService', () => {
spyOn(mockDBServiceInstance, 'login');
component.login();
expect(mockDBServiceInstance.login).toHaveBeenCalled();
});
});
});
An error occurs:
Error: <spyOn> : login() method does not exist
In my pursuit of a solution, I welcome any tips or best practices to address this issue effectively within the Angular framework.
Many thanks