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);
});
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With