I tried to test service, http post, like this code below.
I follow this post for my testing, but I have a error.
My service code:
public CreateProduct(newProd: Product): Observable<boolean> {
.....
let body = newProd.generateUrlencodedParameters(this.currentuser().token);
return this.http.post(API.getUrl(Api.URLS.CreateProduct), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0) {
return true;
}
}
My class Product:
export class Product{
id: number;
prod_number: String;
prod_name: string;
constructor(obj: any) {
this.id= obj.id;
this.prod_number= obj.prod_number;
this.prod_name= obj.prod_name;
}
public generateUrlencodedParameters(token: string, id?: number): string
{
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('prod_number', this.prod_number.toString());
urlSearchParams.append('prod_name', this.prod_name.toString());
urlSearchParams.append('token', token);
return urlSearchParams.toString();
}
}
I tried this code, to testing my service code:
describe('Create Product ', () => {
let trackerFormService: ProductService,
mockService = {
createProduct: jasmine.createSpy('createProduct').and.returnValue(Observable.of('your session object mock goes here'))
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [{
provide: ProductService,
useValue: mockService
}] }); });
beforeEach(inject([ProductService], (trackerFormService) => {
service = trackerFormService;
}));
describe('createProduct', () => {
it('add session ', () => {
let fakeResponse = null;
service.CreateProduct().subscribe((value) => {
fakeResponse = value;
}); }); });});
The result is:
ReferenceError: service is not defined
Please, can you suggest me any idea, how to solve this issue, or any example for testing service post.
Thnx.
Aucun commentaire:
Enregistrer un commentaire