Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While using flush() method : "Automatic conversion to JSON is not supported for response type."

While I'm using the flush() method for testing HTTP requests I have this error:

Automatic conversion to JSON is not supported for response type.

Can you also explain me the goal of the flush() method. I don't really understand it.

The problem was not really solved. We have to add async() method to the "it " function like that : "it('should get the post', async(() => {

import { TestBed } from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing"
import { DataService } from './data.service';
import { Observable } from 'rxjs';
import { Post } from './post.model';
import { HttpClientModule } from '@angular/common/http';

describe('DataService', () => {

  let service: DataService
  let  httpTestingController: HttpTestingController
  let attemptedPost : Post;
  const post = {
    userId: 1,
    id: 1,
    title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  };


  beforeEach(() => { TestBed.configureTestingModule({

    imports : [HttpClientTestingModule,HttpClientModule],
    providers : [DataService]
  });

    service = TestBed.get(DataService);
    httpTestingController = TestBed.get(HttpTestingController)
});

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should get the post', () => {


    service.getPosts().subscribe( (postRetrieved) => {

      attemptedPost=postRetrieved;
    }); 

   const req =  httpTestingController.expectOne('https://jsonplaceholder.typicode.com/posts/1');
   req.flush(attemptedPost);
   // expect(attemptedPost).toEqual(post);

  });
});
like image 538
N.Y Avatar asked May 23 '19 13:05

N.Y


1 Answers

Your error is that subscribe method is async so you try this:

service.getPosts().subscribe( (postRetrieved) => {

      attemptedPost=postRetrieved;

   const req =  httpTestingController.expectOne('https://jsonplaceholder.typicode.com/posts/1');
   req.flush(attemptedPost);
   // expect(attemptedPost).toEqual(post);

});
like image 177
Doflamingo19 Avatar answered Oct 03 '22 04:10

Doflamingo19