I am trying to test my angular2 service by using the mockbackend, but I keep getting this error for my http.post service request.
Here is the error:enter image description here
My service code is :
@Injectable()
export class AuthService {
private _jwt: string;
constructor(private router: Router, private http: Http, private locker: Locker,
private authHttp: AuthHttp, private jwtHelper: JwtHelper) {
this._jwt = localStorage.getItem('id_token');
}
public signIn(user: any) {
let body = JSON.stringify(user);
let self = this;
return this.http.post(loginPath, body, {
headers: contentHeaders})
.map( function (response) { //some code here}
}
And my spec file is as follows:
import { TestBed, async, inject } from '@angular/core/testing';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';
import {
Http, BaseRequestOptions, ResponseOptions, Response, RequestMethod,
HttpModule, XHRBackend
} from '@angular/http';
import { Locker } from 'angular2-locker';
import { AuthHttp, JwtHelper } from 'angular2-jwt';
import { MockBackend, MockConnection } from '@angular/http/testing';
class RouterStub {
navigate() {
}
}
describe('Auth Service Unit Tests', () => {
let authService: AuthService = new AuthService(Router, Http, Locker, AuthHttp, JwtHelper );
let mockbackend;
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
MockBackend,
BaseRequestOptions,
{provide: Router, useClass: RouterStub},
{provide: AuthService, userValue: authService},
{
provide: Http,
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
return new Http(backend, options);
},
deps: [MockBackend, BaseRequestOptions]
}
],
imports: [
HttpModule
]
});
mockbackend = TestBed.get(MockBackend);
/* const baseResponse = new Response(new ResponseOptions({body: 'response'}));
mockbackend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));*/
}));
it('should respond when we subscribe to Sign in', async(() => {
mockbackend.connections.subscribe((connection: MockConnection) =>{
expect(connection.request.method).toBe(RequestMethod.Post);
connection.mockRespond(new Response(new ResponseOptions({status: 201})));
});
let user = {email: 'test@sample.com', password: '12345'};
authService.signIn(user).subscribe((res: Response) => {
expect(res).toBeDefined();
expect(res.status).toBe(200);
});
}));
});
Would highly appreciate any help! Thanks in advance
A quick update (Based on a suggestion by @Will): I made the changes to my service instantiation like shown
{provide: AuthService, useClass: AuthService}
And used it inside my test spec as follows:
authService = TestBed.get(AuthService, null)
But I am still getting the error as follows:
Failed: authService.signIn is not a function
TypeError: authService.signIn is not a function
at src/base.spec.ts:57308:21