I want to test a service, which calls a real backend url and can not find the solution for it. My service has to call data from server and I want to be sure, that the data comes to the service and the service handle it right.
So here is just a simple example of my Login Service:
@Injectable()
export class LoginService {
/**
* The token, which will be stored on the localStorage.
*/
public token: string;
//Eventemitter, for updating the navigation, when the user logs in
@Output() loggedInEm:EventEmitter<any> = new EventEmitter();
constructor(private http: Http) {
// set token if saved in local storage
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
}
login(_mail, _pass): Observable<number> {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var data = {
mail: _mail,
pass: _pass
};
return this.http.post('/login', JSON.stringify(data), {
headers : headers
}).map((response: Response) => {
let res = response.json();
this.logged = res;
});
}
public loggedIn() : boolean {
return this.logged;
}
This is how I want to test it:
describe('Login Service', () => {
let loginService: LoginService;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
],
providers: [
LoginService
],
imports: [
FormsModule,
IonicModule
],
});
inject([LoginService], (service) => {
loginService = service;
});
});
it("Should login user", () => {
loginService.login("[email protected]", "123456");
let loggedIn = loginService.loggedIn();
expect(loggedIn).toBe(true);
});
});
But I get following error: TypeError: Cannot read property 'login' of undefined, so the service must be undefined. I could mock the service, but I want to work it with the real database, which I have on my backend server.
So what could be the problem and how can I solve it?
Kind regards,
Andrej
Try this :