I have a HttpClient request that needs to be tested. Below is the test code I am using:
import { TestBed, inject } from '@angular/core/testing';
import { AviorBackendService } from './avior-backend.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpEventType, HttpEvent } from '@angular/common/http';
import { User } from '../models/user.model';
describe('AviorBackendService', () => {
let httpTestingController: HttpTestingController;
let service: AviorBackendService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [AviorBackendService],
});
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(AviorBackendService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('expects the service to fetch data with proper sorting', () => {
console.log(service.SERVICE_URL);
const mockResponse = [{
_id: 25,
loginId: 'string',
lastname: 'string',
firstname: 'string',
password: 'string',
eMail: 'string',
} as User];
/* service.getUserCollection().subscribe(data => {
expect(data.firstName).toEqual('Namehere');
}); */
// const req = httpTestingController
// .expectOne(req => req.method === 'GET' && req.url === 'http://example.org');
const req = httpTestingController.expectOne('http://localhost:3000/users');
expect(req.request.method).toEqual('POST');
console.log('REQ REQUEST URL:', req.request.url);
// send the response to the subscribe.
req.flush(mockResponse as any);
});
});
The issue arises when running the req test which fails with the error
Error: Expected one matching request for criteria "Match URL: http://localhost:3000/users", found none.
. Additionally, Property 'firstName' does not exist on type 'User[]'
triggers an error on expect(data.firstName).toEqual('Namehere');
(which has been commented out). Attempts to troubleshoot following suggestions here were unsuccessful.
Here is my user-collection.model.ts:
import { User } from './user.model';
export interface UserCollection {
user: User[];
}
And this is my user.model.ts:
import { Role } from './role';
// was class and not interface!
export interface User {
_id: number;
mandator?: number;
loginId: string;
lastname: string;
firstname: string;
password: string;
eMail: string;
group?: string;
role?: Role;
active?: boolean;
token?: string;
}
Lastly, the backend code snippet:
export class AviorBackendService {
readonly SERVICE_URL = 'http://localhost:3000/';
........
getUserCollection() {
// withCredentials is very important as it passes the JWT cookie needed to authenticate
return this.client.get<User[]>(this.SERVICE_URL + 'users', { withCredentials: true });
}