Reputation: 596
Hi can anyone tell me why this service test is always passing when it should fail? I am using Jest if that matters. The data is 1 object in an array but the test expects 5 and still passes! (The console log does get hit and returns the data); I have been unable to trigger the expect calls in the subscribe and I do not understand why.
The console log is working, but the expect is not. I must be doing something really dumb, but not sure what. Can anyone explain what is wrong?
import { TestBed, inject, getTestBed } from '@angular/core/testing';
import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';
import { DataHandlerService } from './data-handler.service';
describe('DataHandlerService', () => {
let injector: TestBed;
let service: DataHandlerService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [DataHandlerService]
});
injector = getTestBed();
httpMock = TestBed.get(HttpTestingController);
service = TestBed.get(DataHandlerService);
});
afterEach(() => {
httpMock.verify();
});
it('should be created', () => {
service = TestBed.get(DataHandlerService);
expect(service).toBeTruthy();
});
describe('getData()', () => {
it('should trigger call', () => {
const mockEvt = [{
audio: "N",
city: "Madrid",
country: "Spain",
date: "1930-01-01",
}];
service.getData('/test').subscribe(evtData => {
console.log('CALLING ..... ', evtData);
expect(evtData.length).toEqual(5);
expect(evtData[0].country).toBe('France');
});
const req = httpMock.expectOne("/test");
expect(req.request.method).toBe('GET');
req.flush(mockEvt);
});
});
});
This is the service I am testing. It is basic right now. Will add more details after the core test is working.
@Injectable({
providedIn: 'root'
})
export class DataHandlerService {
constructor(private http: HttpClient) { }
getData(urlToFetch: string): Observable<any[]> {
return this.http.get<any[]>(urlToFetch);
}
}
Upvotes: 0
Views: 876
Reputation: 596
Hmmm … looks like if I use async() without done() then the tests run as I expect.
it('should trigger call’, async(() => {
//// test info here
//// means the subscribe is running correctly and the expects get triggered
}));
Upvotes: 1