I am trying to create unit tests for a full-stack application I am writing to practice learning angular. I am trying to create mock requests to test the functions of my frontend without actually making requests to the backend. This test keeps saying that it is not receving a put request, although the function that sends the put request is being entered. The put request is being sent when the angular server is live, just not when the test is being ran.
The test
it('Testing OnSubmit with valid input', async () => {
const httpTesting = TestBed.inject(HttpTestingController);
const expectedUser = {id: 1, name: 'Test', Bankroll: 500, hours: 100, winrate: 5};
//const alertSpy = spyOn(window, 'alert');
const expectedSessions = [
{ id: 1, user_id: 1, buyIn: 300, cashOut: 400, timePlayed: 3 },
{ id: 2, user_id: 1, buyIn: 100, cashOut: 400, timePlayed: 3 },
{ id: 3, user_id: 1, buyIn: 200, cashOut: 400, timePlayed: 3 }
];
component.newSession = {user_id: 1, buyIn: 100, cashOut: 200, timePlayed: 5};
component.onSubmit();
await fixture.whenStable();
const submitReq = httpTesting.expectOne({ method: 'POST', url: 'http://localhost:3000/api/v1/sessions' }).flush({});
const updateReq = httpTesting.expectOne({method: 'PUT', url: 'http://localhost:3000/api/v1/users/1'}).flush('');
const getReq = httpTesting.expectOne({ method: 'GET', url: 'http://localhost:3000/api/v1/users/1' }).flush(expectedUser);
const sessionsByReq = httpTesting.expectOne({ method: 'GET', url: 'http://localhost:3000/api/v1/sessions' }).flush(expectedSessions);
//expect(window.alert).toHaveBeenCalledTimes(0);
/* expect(component.newSession).toEqual({
user_id: 1,
buyIn: 0,
cashOut: 0,
timePlayed: 0
});*/
//expect(component.user1).toEqual(expectedUser);
//expect(component.updatedSessions).toEqual(expectedSessions);
expect(true).toEqual(true);
})
The function being tested
async onSubmit(): Promise<void> {
const userID = 1;
if(this.newSession.buyIn > 0 && this.newSession.cashOut >= 0 && this.newSession.timePlayed > 0) {
await this.dashService.submitSession(this.newSession);
console.log('sent post')
} else {
alert("Invalid input");
}
await this.dashService.updateUser();
this.user1 = await this.dashService.getUser(userID);
this.updatedSessions = (await this.dashService.sessionsByUser()).sort((a: session, b: session ) => a.id - b.id);
this.newSession = {
user_id: 1,
buyIn: 0,
cashOut: 0,
timePlayed: 0
}
}
The function to make the put request.
async updateUser(): Promise<any> {
console.log('PUT REQ ENTERED')
return await lastValueFrom(this.http.put(`${this.urlPut}/1`, ''));
}