From 5bef72e5a49964a7367840faa39a12ccec174ac3 Mon Sep 17 00:00:00 2001 From: jaimeeg5 Date: Fri, 13 Nov 2026 10:48:07 +0100 Subject: [PATCH 1/2] feat: add review update backend and tests --- .../controller/ReviewsRestController.java | 17 +- .../pcmod/security/SecurityConfig.java | 1 + .../pcmod/service/ReviewsService.java | 59 +++-- .../pcmod/e2e/api/ReviewsSystemTests.java | 217 ++++++++++++++++++ .../integration/ReviewsIntegrationTests.java | 134 +++++++++++ .../pcmod/unit/ReviewsUnitTests.java | 139 +++++++++++ 6 files changed, 548 insertions(+), 19 deletions(-) diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/controller/ReviewsRestController.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/controller/ReviewsRestController.java index 0bdf33e..97a4f00 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/controller/ReviewsRestController.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/controller/ReviewsRestController.java @@ -1,5 +1,7 @@ package es.codeurjcstudents.pcmod.controller; +import static org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentRequest; + import java.net.URI; import java.security.Principal; @@ -11,12 +13,11 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import static org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentRequest; - import es.codeurjcstudents.pcmod.dto.ReviewDTO; import es.codeurjcstudents.pcmod.model.Review; import es.codeurjcstudents.pcmod.service.ReviewsService; @@ -60,4 +61,16 @@ public void deleteReview(@PathVariable long id, @PathVariable long reviewId) { reviewsService.delete(id, reviewId); } + @PutMapping("/{reviewId}") + public ResponseEntity updateComponent(@RequestBody ReviewDTO updatedData, @PathVariable long id, @PathVariable long reviewId) { + + Review newReviewData = reviewsService.toDomain(updatedData); + Review updatedReview = reviewsService.updateReview(newReviewData, id, reviewId); + + URI location = fromCurrentRequest().buildAndExpand(updatedReview.getId()).toUri(); + + return ResponseEntity.created(location).body(reviewsService.toDTO(updatedReview)); + + } + } diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/security/SecurityConfig.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/security/SecurityConfig.java index 237268b..0eafcaf 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/security/SecurityConfig.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/security/SecurityConfig.java @@ -61,6 +61,7 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) { http.authorizeHttpRequests(authorize -> authorize .requestMatchers(HttpMethod.POST, "/api/v1/components/*/reviews/").hasRole("REGISTERED_USER") .requestMatchers(HttpMethod.DELETE, "/api/v1/components/*/reviews/*").hasRole("REGISTERED_USER") + .requestMatchers(HttpMethod.PUT, "/api/v1/components/*/reviews/*").hasRole("REGISTERED_USER") .requestMatchers(HttpMethod.GET, "/api/v1/users/me").hasRole("REGISTERED_USER") .requestMatchers(HttpMethod.POST, "/api/v1/users/*/image").hasRole("REGISTERED_USER") .requestMatchers(HttpMethod.DELETE, "/api/v1/users/**").hasRole("REGISTERED_USER") diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java index d48e39d..b9f5d3c 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java @@ -86,6 +86,48 @@ public Review save(Review review, long userId, long componentId) { return reviewRepository.save(review); } + @PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)") + public void delete(long componentId, long reviewId) { + + Optional reviewToDelete = reviewRepository.findById(reviewId); + + if ((reviewToDelete.isPresent()) && (reviewToDelete.get().getComponent().getId() != componentId)) { + throw new NoSuchElementException("La reseña no pertenece a ese componente."); + } + + if (reviewToDelete.isPresent()) { + + reviewRepository.deleteById(reviewId); + + } + + } + + @PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)") + public Review updateReview(Review newReviewData, long componentId, long reviewId) { + + Optional reviewToUpdate = reviewRepository.findById(reviewId); + + if ((reviewToUpdate.isPresent()) && (reviewToUpdate.get().getComponent().getId() != componentId)) { + throw new NoSuchElementException("La reseña no pertenece a ese componente."); + } + + List errors = validateReview(newReviewData); + + if (!errors.isEmpty()) { + throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + } + + Review review = reviewRepository.findById(reviewId).orElseThrow(); + review.setTitle(newReviewData.getTitle()); + review.setMessage(newReviewData.getMessage()); + review.setRating(newReviewData.getRating()); + review.setDate(LocalDate.now(ZoneId.of("Europe/Madrid"))); + + return reviewRepository.save(review); + + } + public boolean hasUserReviewed(Long componentId, Long userId) { return reviewRepository.existsByComponentIdAndUserId(componentId, userId); } @@ -123,23 +165,6 @@ public void validateRating(Review review, List errors) { } - @PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)") - public void delete(long componentId, long reviewId) { - - Optional reviewToDelete = reviewRepository.findById(reviewId); - - if ((reviewToDelete.isPresent()) && (reviewToDelete.get().getComponent().getId() != componentId)) { - throw new NoSuchElementException("La reseña no pertenece a ese componente."); - } - - if (reviewToDelete.isPresent()) { - - reviewRepository.deleteById(reviewId); - - } - - } - public boolean isOwner(long reviewId, String usernameId) { Optional review = reviewRepository.findById(reviewId); diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java index 2d62848..d676807 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java @@ -436,4 +436,221 @@ public void deleteReviewWithWrongComponentId() { } + @Test + public void putReviewAsNoLoggedIn() { + given() + .header("Content-Type", "application/json") + .body(""" + { + "title": "sample_title", + "message": "sample_message", + "rating": 5 + } + """) + .when().put("/components/2/reviews/1") + .then().statusCode(401).contentType(ContentType.JSON) + .body("error", equalTo("Unauthorized")); + } + + @Test + public void putReviewAsRegisteredUserNoAdmin() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "user@example.com", + "password": "userpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "title": "sample_title", + "message": "sample_message", + "rating": 5 + } + """) + .when().put("/components/2/reviews/1") + .then().statusCode(201).contentType(ContentType.JSON) + .body("id", notNullValue()) + .body("title", equalTo("sample_title")) + .body("message", equalTo("sample_message")) + .body("rating", equalTo(5)); + } + + @Test + public void putOtherUserReviewAsRegisteredUserNoAdmin() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "user@example.com", + "password": "userpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "title": "sample_title", + "message": "sample_message", + "rating": 5 + } + """) + .when().put("/components/2/reviews/2") + .then().statusCode(403).contentType(ContentType.JSON) + .body("error", equalTo("Forbidden")); + } + + @Test + public void putReviewsAsAdmin() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "title": "sample_title", + "message": "sample_message", + "rating": 5 + } + """) + .when().put("/components/2/reviews/1") + .then().statusCode(201).contentType(ContentType.JSON) + .body("id", notNullValue()) + .body("title", equalTo("sample_title")) + .body("message", equalTo("sample_message")) + .body("rating", equalTo(5)); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "title": "sample_title", + "message": "sample_message", + "rating": 5 + } + """) + .when().put("/components/2/reviews/2") + .then().statusCode(201).contentType(ContentType.JSON) + .body("id", notNullValue()) + .body("title", equalTo("sample_title")) + .body("message", equalTo("sample_message")) + .body("rating", equalTo(5)); + } + + @Test + public void putVoidReviewData() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "title": "", + "message": "", + "rating": "" + } + """) + .when().put("/components/2/reviews/1") + .then().statusCode(500).contentType(ContentType.JSON) + .body("message", equalTo( + "Validación fallida:\n• El título es obligatorio.\n• El mensaje es obligatorio.\n• La valoración es obligatoria.")); + } + + @Test + public void putNullComponentData() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "title": null, + "message": null, + "rating": null + } + """) + .when().put("/components/2/reviews/1") + .then().statusCode(500).contentType(ContentType.JSON) + .body("message", equalTo( + "Validación fallida:\n• El título es obligatorio.\n• El mensaje es obligatorio.\n• La valoración es obligatoria.")); + } + + @Test + public void putBadNumReviewData() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "title": "sample_title", + "message": "sample_message", + "rating": -5 + } + """) + .when().put("/components/2/reviews/1") + .then().statusCode(500).contentType(ContentType.JSON) + .body("status", equalTo(500)) + .body("message", equalTo( + "Validación fallida:\n• La valoración del producto ha de estar entre 1 y 5.")); + } + } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java index d984f9f..a089af8 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java @@ -490,4 +490,138 @@ void deleteReviewOfWrongComponent() { } + @Test + void updateReviewAsNoRegisteredUser() { + Component component = componentsRepository.findAll().getFirst(); + Review review = reviewsRepository.findAll().getFirst(); + + Review updatedReview = new Review("sample_title", "sample_message", Integer.valueOf(5)); + + assertThrows(AuthenticationCredentialsNotFoundException.class, + () -> reviewsService.updateReview(updatedReview, component.getId(), review.getId())); + } + + @Test + void updateReviewAsRegisteredUserNoAdmin() { + Component component = componentsRepository.findAll().getFirst(); + Review review = reviewsRepository.findAll().getFirst(); + + Review updatedReview = new Review("sample_title", "sample_message", Integer.valueOf(5)); + + User user = usersRepository.findByEmail("testuser1@example.com").orElseThrow(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(user.getId().toString()) + .password("").authorities("ROLE_REGISTERED_USER").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER")))); + + Review savedReview = reviewsService.updateReview(updatedReview, component.getId(), review.getId()); + + assertEquals("sample_title", savedReview.getTitle()); + assertEquals("sample_message", savedReview.getMessage()); + assertEquals(Integer.valueOf(5), savedReview.getRating()); + } + + @Test + void updateOtherUserReviewAsRegisteredUserNoAdmin() { + Component component = componentsRepository.findAll().getFirst(); + Review review = reviewsRepository.findAll().getLast(); + + Review updatedReview = new Review("sample_title", "sample_message", Integer.valueOf(5)); + + User user = usersRepository.findByEmail("testuser1@example.com").orElseThrow(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(user.getId().toString()) + .password("").authorities("ROLE_REGISTERED_USER").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER")))); + + assertThrows(AuthorizationDeniedException.class, + () -> reviewsService.updateReview(updatedReview, component.getId(), review.getId())); + } + + @Test + void updateReviewAsAdmin() { + Component component = componentsRepository.findAll().getFirst(); + Review reviewUser = reviewsRepository.findAll().getFirst(); + Review reviewAdmin = reviewsRepository.findAll().getLast(); + + Review updatedReview = new Review("sample_title", "sample_message", Integer.valueOf(5)); + + User user = usersRepository.findByEmail("testuser1@example.com").orElseThrow(); + + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review savedUserReview = reviewsService.updateReview(updatedReview, component.getId(), reviewUser.getId()); + Review savedAdminReview = reviewsService.updateReview(updatedReview, component.getId(), reviewAdmin.getId()); + + assertEquals("sample_title", savedUserReview.getTitle()); + assertEquals("sample_message", savedUserReview.getMessage()); + assertEquals(Integer.valueOf(5), savedUserReview.getRating()); + assertEquals(user.getId(), savedUserReview.getUser().getId()); + assertEquals("sample_title", savedAdminReview.getTitle()); + assertEquals("sample_message", savedAdminReview.getMessage()); + assertEquals(Integer.valueOf(5), savedAdminReview.getRating()); + + } + + @Test + void updateVoidReview() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + Review review = reviewsRepository.findAll().getFirst(); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review updatedReview = new Review("", "", null); + + assertThrows(IllegalArgumentException.class, + () -> reviewsService.updateReview(updatedReview, component.getId(), review.getId())); + } + + @Test + void updateNullReview() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + Review review = reviewsRepository.findAll().getFirst(); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review updatedReview = new Review(null, null, null); + + assertThrows(IllegalArgumentException.class, + () -> reviewsService.updateReview(updatedReview, component.getId(), review.getId())); + } + + @Test + void updateBadFormatReview() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + Component component = componentsRepository.findAll().get(0); + Review review = reviewsRepository.findAll().getFirst(); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review updatedReview = new Review("sample_title", "sample_message", Integer.valueOf(-5)); + + assertThrows(IllegalArgumentException.class, + () -> reviewsService.updateReview(updatedReview, component.getId(), review.getId())); + } + } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java index 852db25..b24e5c9 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -498,4 +499,142 @@ public void testIsOwnerWithNoPresentReview() { assertFalse(reviewsService.isOwner(1L, "1")); } + + @Test + public void testUpdateReview() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + UsersRepository usersRepository = mock(UsersRepository.class); + ReviewMapper reviewMapper = mock(ReviewMapper.class); + ReviewsRepository reviewsRepository = mock(ReviewsRepository.class); + ReviewsService reviewsService = new ReviewsService(reviewsRepository, reviewMapper, componentsRepository, usersRepository ); + + Component component = new Component("sample_name", "sample_message", ComponentType.CPU, "sample_brand", BigDecimal.valueOf(100.00), 5); + component.setId(1L); + + User user = new User("user", "test", "userTest", "c/testaddress", "testuser@example.com", + passwordEncoder.encode("pass"), "REGISTERED_USER"); + + Review review = new Review("sample_title", "sample_message", 5); + review.setComponent(component); + Review reviewToUpdate = new Review("sample_title_updated", "sample_message_updated", 1); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + when(reviewsRepository.save(any(Review.class))).thenReturn(review); + + Review updatedReview = reviewsService.updateReview(reviewToUpdate, 1L, 1L); + + assertEquals(reviewToUpdate.getTitle(), updatedReview.getTitle()); + assertEquals(reviewToUpdate.getMessage(), updatedReview.getMessage()); + assertEquals(reviewToUpdate.getRating(), updatedReview.getRating()); + verify(reviewsRepository).save(any(Review.class)); + } + + @Test + public void testUpdateVoidReviewData() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + UsersRepository usersRepository = mock(UsersRepository.class); + ReviewMapper reviewMapper = mock(ReviewMapper.class); + ReviewsRepository reviewsRepository = mock(ReviewsRepository.class); + ReviewsService reviewsService = new ReviewsService(reviewsRepository, reviewMapper, componentsRepository, usersRepository ); + + Component component = new Component("sample_name", "sample_message", ComponentType.CPU, "sample_brand", BigDecimal.valueOf(100.00), 5); + component.setId(1L); + + User user = new User("user", "test", "userTest", "c/testaddress", "testuser@example.com", + passwordEncoder.encode("pass"), "REGISTERED_USER"); + + Review review = new Review("", "", null); + review.setComponent(component); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.updateReview(review, 1L, 1L)); + verify(reviewsRepository, never()).save(any(Review.class)); + + } + + @Test + public void testUpdateNullReviewData() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + UsersRepository usersRepository = mock(UsersRepository.class); + ReviewMapper reviewMapper = mock(ReviewMapper.class); + ReviewsRepository reviewsRepository = mock(ReviewsRepository.class); + ReviewsService reviewsService = new ReviewsService(reviewsRepository, reviewMapper, componentsRepository, usersRepository ); + + Component component = new Component("sample_name", "sample_message", ComponentType.CPU, "sample_brand", BigDecimal.valueOf(100.00), 5); + component.setId(1L); + + User user = new User("user", "test", "userTest", "c/testaddress", "testuser@example.com", + passwordEncoder.encode("pass"), "REGISTERED_USER"); + + Review review = new Review(null, null, null); + review.setComponent(component); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.updateReview(review, 1L, 1L)); + verify(reviewsRepository, never()).save(any(Review.class)); + + } + + @Test + public void testUpdateBadNumReviewData() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + UsersRepository usersRepository = mock(UsersRepository.class); + ReviewMapper reviewMapper = mock(ReviewMapper.class); + ReviewsRepository reviewsRepository = mock(ReviewsRepository.class); + ReviewsService reviewsService = new ReviewsService(reviewsRepository, reviewMapper, componentsRepository, usersRepository ); + + Component component = new Component("sample_name", "sample_message", ComponentType.CPU, "sample_brand", BigDecimal.valueOf(100.00), 5); + component.setId(1L); + + User user = new User("user", "test", "userTest", "c/testaddress", "testuser@example.com", + passwordEncoder.encode("pass"), "REGISTERED_USER"); + + Review review = new Review("sample_title", "sample_message", -5); + review.setComponent(component); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.updateReview(review, 1L, 1L)); + verify(reviewsRepository, never()).save(any(Review.class)); + + } + + @Test + public void testUpdateReviewOfWrongComponent() { + + ReviewsRepository reviewsRepository = mock(ReviewsRepository.class); + ReviewsService reviewsService = new ReviewsService(reviewsRepository, null, null, null ); + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + + Component component = new Component("sample_name", "sample_message", ComponentType.CPU, "sample_brand", BigDecimal.valueOf(100.00), 5); + Component otherComponent = new Component("sample_name2", "sample_message2", ComponentType.CPU, "sample_brand2", BigDecimal.valueOf(100.00), 5); + component.setId(1L); + otherComponent.setId(2L); + + Review review = new Review("sample_title", "sample_message", 5); + review.setComponent(component); + + Review updatedReview = new Review("sample_title_updated", "sample_message_updated", Integer.valueOf(1)); + + when(reviewsRepository.findById(1L)).thenReturn(java.util.Optional.of(review)); + when(componentsRepository.findById(2L)).thenReturn(java.util.Optional.of(otherComponent)); + + assertThrows(NoSuchElementException.class, () -> reviewsService.updateReview(updatedReview, 2L, 1L)); + verify(reviewsRepository, never()).deleteById(1L); + + } } From dcf67a88f9346afb6f507afa86872d31f3c4b036 Mon Sep 17 00:00:00 2001 From: jaimeeg5 Date: Sat, 14 Nov 2026 11:11:00 +0100 Subject: [PATCH 2/2] feat: add review frontend and tests fix: style errors --- .../pcmod/e2e/ui/HomePageSystemTests.java | 3 +- .../pcmod/e2e/ui/ReviewsSystemTests.java | 171 +++++++++ frontend/app/app.css | 56 ++- frontend/app/components/componentsForm.tsx | 4 +- frontend/app/components/reviewCard.tsx | 97 +++-- frontend/app/components/reviewForm.tsx | 32 +- frontend/app/hooks/use-review-form.ts | 53 +++ frontend/app/routes/components-create.tsx | 2 +- frontend/app/routes/components-update.tsx | 2 +- frontend/app/routes/detail-component.tsx | 59 ++- frontend/app/routes/login.tsx | 2 +- frontend/app/routes/register.tsx | 2 +- frontend/app/services/reviews-service.ts | 30 ++ .../ComponentDetailPage.integration.test.tsx | 237 +++++++++++- .../tests/unit/ComponentDetailPage.test.tsx | 360 +++++++++++++++++- 15 files changed, 1023 insertions(+), 87 deletions(-) create mode 100644 frontend/app/hooks/use-review-form.ts diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/HomePageSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/HomePageSystemTests.java index 48fe982..eec0c88 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/HomePageSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/HomePageSystemTests.java @@ -62,8 +62,7 @@ public void loadHomePage() { wait.until(ExpectedConditions.numberOfElementsToBe(recentComponentNames, 3)); assertThat(driver.findElements(recentComponentNames)) .extracting(WebElement::getText) - .containsExactly( - "testComponent", + .contains( "Corsair iCUE LINK 3500X RGB", "Kingston FURY Beast"); diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/ReviewsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/ReviewsSystemTests.java index c8043c6..d934a83 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/ReviewsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/ui/ReviewsSystemTests.java @@ -129,6 +129,8 @@ public void reviewsOptionsAsNonLoggedInTest() { driver.get("http://localhost:5173/components/2"); assertThat(driver.findElements(By.id("save-review-button"))).isEmpty(); + assertThat(driver.findElements(By.id("update-review-button-1"))).isEmpty(); + assertThat(driver.findElements(By.id("update-review-button-2"))).isEmpty(); assertThat(driver.findElements(By.id("delete-review-button-1"))).isEmpty(); assertThat(driver.findElements(By.id("delete-review-button-2"))).isEmpty(); @@ -143,9 +145,12 @@ public void reviewsOptionsAsLoggedInNoAdminWithReviewTest() { driver.get("http://localhost:5173/components/2"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("update-review-button-1"))); wait.until(ExpectedConditions.presenceOfElementLocated(By.id("delete-review-button-1"))); assertThat(driver.findElements(By.id("save-review-button"))).isEmpty(); + assertThat(driver.findElements(By.id("update-review-button-1"))).isNotEmpty(); + assertThat(driver.findElements(By.id("update-review-button-2"))).isEmpty(); assertThat(driver.findElements(By.id("delete-review-button-1"))).isNotEmpty(); assertThat(driver.findElements(By.id("delete-review-button-2"))).isEmpty(); @@ -173,10 +178,14 @@ public void reviewsOptionsAsAdminWithReviewTest() { driver.get("http://localhost:5173/components/2"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("update-review-button-1"))); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("update-review-button-2"))); wait.until(ExpectedConditions.presenceOfElementLocated(By.id("delete-review-button-1"))); wait.until(ExpectedConditions.presenceOfElementLocated(By.id("delete-review-button-2"))); assertThat(driver.findElements(By.id("save-review-button"))).isEmpty(); + assertThat(driver.findElements(By.id("update-review-button-1"))).isNotEmpty(); + assertThat(driver.findElements(By.id("update-review-button-2"))).isNotEmpty(); assertThat(driver.findElements(By.id("delete-review-button-1"))).isNotEmpty(); assertThat(driver.findElements(By.id("delete-review-button-2"))).isNotEmpty(); @@ -353,4 +362,166 @@ public void cancelDeleteComponentClosingModalTest() { } + @Test + public void updateAsLoggedInNoAdminTest() { + + login("user@example.com", "userpass"); + + driver.get("http://localhost:5173/components/4"); + scrollToAndClick(By.id("update-review-button-4")); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("title"))); + driver.findElement(By.id("title")).clear(); + driver.findElement(By.id("title")).sendKeys("updated_title"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("message"))); + driver.findElement(By.id("message")).clear(); + driver.findElement(By.id("message")).sendKeys("updated_message"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("rating"))); + driver.findElement(By.id("rating")).clear(); + driver.findElement(By.id("rating")).sendKeys("1"); + scrollToAndClick(By.id("save-review-button")); + + driver.get("http://localhost:5173/components/4"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("usernameReview-1"))); + String reviewUsername = driver.findElement(By.id("usernameReview-1")).getText(); + assertThat(reviewUsername).isEqualTo("user_example"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-title-4"))); + String reviewTitle = driver.findElement(By.id("review-title-4")).getText(); + assertThat(reviewTitle).isEqualTo("updated_title"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-message-4"))); + String reviewMessage = driver.findElement(By.id("review-message-4")).getText(); + assertThat(reviewMessage).isEqualTo("updated_message"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-valoration-4"))); + String reviewRating = driver.findElement(By.id("review-valoration-4")).getText(); + assertThat(reviewRating).isEqualTo("Valoración del producto: ★☆☆☆☆ 1/5"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-average-rating"))); + String loadedComponentAverageRating = driver.findElement(By.id("component-average-rating")).getText(); + assertThat(loadedComponentAverageRating).isEqualTo("Puntuación media: ★☆☆☆☆ 1/5 (1 reseña(s))"); + + } + + @Test + public void updateAsAdminTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/4"); + scrollToAndClick(By.id("update-review-button-4")); + WebElement editForm = wait.until( + ExpectedConditions.visibilityOfElementLocated(By.id("edit-review-form")) + ); + editForm.findElement(By.id("title")).clear(); + editForm.findElement(By.id("title")).sendKeys("updated_title"); + editForm.findElement(By.id("message")).clear(); + editForm.findElement(By.id("message")).sendKeys("updated_message"); + editForm.findElement(By.id("rating")).clear(); + editForm.findElement(By.id("rating")).sendKeys("1"); + scrollToAndClick(By.id("save-review-button")); + + driver.get("http://localhost:5173/components/4"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("usernameReview-1"))); + String reviewUsername = driver.findElement(By.id("usernameReview-1")).getText(); + assertThat(reviewUsername).isEqualTo("user_example"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-title-4"))); + String reviewTitle = driver.findElement(By.id("review-title-4")).getText(); + assertThat(reviewTitle).isEqualTo("updated_title"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-message-4"))); + String reviewMessage = driver.findElement(By.id("review-message-4")).getText(); + assertThat(reviewMessage).isEqualTo("updated_message"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-valoration-4"))); + String reviewRating = driver.findElement(By.id("review-valoration-4")).getText(); + assertThat(reviewRating).isEqualTo("Valoración del producto: ★☆☆☆☆ 1/5"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("component-average-rating"))); + String loadedComponentAverageRating = driver.findElement(By.id("component-average-rating")).getText(); + assertThat(loadedComponentAverageRating).isEqualTo("Puntuación media: ★☆☆☆☆ 1/5 (1 reseña(s))"); + + } + + @Test + public void updateVoidReviewTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/4"); + + scrollToAndClick(By.id("update-review-button-4")); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("title"))); + driver.findElement(By.id("title")).clear(); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("message"))); + driver.findElement(By.id("message")).clear(); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("rating"))); + driver.findElement(By.id("rating")).clear(); + scrollToAndClick(By.id("save-review-button")); + + assertThat(driver.findElement(By.id("invalid-title")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-title")).getText()) + .isEqualTo("Por favor, ingrese un título válido."); + assertThat(driver.findElement(By.id("invalid-message")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-message")).getText()) + .isEqualTo("Por favor, ingrese un mensaje válido."); + assertThat(driver.findElement(By.id("invalid-rating")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-rating")).getText()) + .isEqualTo("Por favor, ingrese una valoración válida."); + + } + + @Test + public void updateInvalidFormatReviewTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/4"); + scrollToAndClick(By.id("update-review-button-4")); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("title"))); + driver.findElement(By.id("title")).clear(); + driver.findElement(By.id("title")).sendKeys("updated_title"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("message"))); + driver.findElement(By.id("message")).clear(); + driver.findElement(By.id("message")).sendKeys("updated_message"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("rating"))); + driver.findElement(By.id("rating")).clear(); + driver.findElement(By.id("rating")).sendKeys("-1"); + scrollToAndClick(By.id("save-review-button")); + + assertThat(driver.findElement(By.id("invalid-rating")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("invalid-rating")).getText()) + .isEqualTo("Por favor, ingrese una valoración válida."); + + } + + @Test + public void cancelUpdateReviewTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/4"); + scrollToAndClick(By.id("update-review-button-4")); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("title"))); + driver.findElement(By.id("title")).clear(); + driver.findElement(By.id("title")).sendKeys("updated_title_cancel"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("message"))); + driver.findElement(By.id("message")).clear(); + driver.findElement(By.id("message")).sendKeys("updated_message_cancel"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("rating"))); + driver.findElement(By.id("rating")).clear(); + driver.findElement(By.id("rating")).sendKeys("2"); + scrollToAndClick(By.name("cancel-review-button")); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("usernameReview-1"))); + String reviewUsername = driver.findElement(By.id("usernameReview-1")).getText(); + assertThat(reviewUsername).isEqualTo("user_example"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-title-4"))); + String reviewTitle = driver.findElement(By.id("review-title-4")).getText(); + assertThat(reviewTitle).isNotEqualTo("updated_title_cancel"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-message-4"))); + String reviewMessage = driver.findElement(By.id("review-message-4")).getText(); + assertThat(reviewMessage).isNotEqualTo("updated_message_cancel"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-valoration-4"))); + String reviewRating = driver.findElement(By.id("review-valoration-4")).getText(); + assertThat(reviewRating).isNotEqualTo("2"); + + + } + } diff --git a/frontend/app/app.css b/frontend/app/app.css index b6882ae..c2b7189 100644 --- a/frontend/app/app.css +++ b/frontend/app/app.css @@ -514,6 +514,44 @@ body { background-color: var(--color-brand-dark); } +.review-form-actions { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; +} + +.review-form-actions .pcmod-danger-button, +.review-form-actions .pcmod-review-update-button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.45rem; + padding: 0.6rem 0.8rem; + border: 1px solid transparent; + border-radius: 8px; + font-family: var(--font-sans); + font-size: 0.9rem; + font-weight: 500; +} + +.review-form-actions .pcmod-review-update-button { + color: #ffffff; + background-color: var(--color-principal); +} + +.review-form-actions .pcmod-review-update-button:hover, +.review-form-actions .pcmod-review-update-button:focus-visible { + color: #ffffff; + background-color: var(--color-brand-dark); + transform: translateY(-1px); +} + +.review-form-actions .pcmod-review-update-button:disabled { + color: #ffffff; + background-color: var(--color-muted); + transform: none; +} + /* Component detail */ .main:has(.component-data) { @@ -848,11 +886,12 @@ body { display: inline-flex; align-items: center; justify-content: center; + box-sizing: border-box; width: 38px; height: 38px; margin-top: 1rem; margin-right: 0.5rem; - padding: 0.45rem; + padding: 0.45rem !important; border-radius: 6px; } @@ -861,6 +900,21 @@ body { padding-top: 0.25rem; } +.custom-component-form > .pcmod-danger-button, +.custom-component-form > .pcmod-button { + display: inline-flex; + align-items: center; + justify-content: center; + width: auto; + min-width: 150px; + min-height: 46px; + margin: 0 0.75rem 0.75rem 0; + padding: 0.75rem 1.25rem; + box-sizing: border-box; + text-decoration: none; + vertical-align: middle; +} + /* Modal */ .modal-content { diff --git a/frontend/app/components/componentsForm.tsx b/frontend/app/components/componentsForm.tsx index ee7a008..aaed958 100644 --- a/frontend/app/components/componentsForm.tsx +++ b/frontend/app/components/componentsForm.tsx @@ -110,13 +110,13 @@ const cancelPath = component?.id !== undefined ? `/components/${component.id}` : - Cancelar + Cancelar ); diff --git a/frontend/app/components/reviewCard.tsx b/frontend/app/components/reviewCard.tsx index 3258622..86e44f6 100644 --- a/frontend/app/components/reviewCard.tsx +++ b/frontend/app/components/reviewCard.tsx @@ -1,9 +1,13 @@ import { useState } from "react"; import { Button, Image, Modal } from "react-bootstrap"; -import { ArrowLeft, Trash } from "react-bootstrap-icons"; +import { ArrowLeft, ExclamationCircleFill, PencilSquare, Trash } from "react-bootstrap-icons"; import type ReviewDTO from "~/dtos/ReviewDTO"; -import { deleteReview } from "~/services/reviews-service"; +import { deleteReview, updateReview } from "~/services/reviews-service"; import { useUserStore } from "~/stores/user-store"; +import ReviewForm from "./reviewForm"; +import { type ReviewFormValues } from "~/utils/review-form-utils"; +import { useRevalidator } from "react-router"; +import { useReviewForm } from "~/hooks/use-review-form"; interface ReviewCardProps { review: ReviewDTO; @@ -20,9 +24,27 @@ function convertRatingToStars(rating: number) { export default function ReviewCard({ review, onDelete }: Readonly) { let { user } = useUserStore(); + const revalidator = useRevalidator(); + const [isEditing, setIsEditing] = useState(false); const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); + const initialState: ReviewFormValues = { + title: review.title ?? "", + message: review.message ?? "", + rating: review.rating ?? 0, + }; + + const reviewForm = useReviewForm({ + initialState, + submitAction: async (values) => { + await updateReview(review.componentId, review.id, values.title, values.message, values.rating); + setIsEditing(false); + await revalidator.revalidate(); + }, + defaultErrorMessage:"Hubo un error al actualizar la reseña. Por favor, inténtalo de nuevo.", + }); + async function handleDeleteReview() { try { await deleteReview(review.componentId, review.id); @@ -35,29 +57,58 @@ export default function ReviewCard({ review, onDelete }: Readonly -
-
- userImage -

{review.user.username}

-

{review.date}

-
-
-

{review.title}

-

{review.message}

-

Valoración del producto: {convertRatingToStars(review.rating)} {review.rating}/5

- {((user?.id === review.user.id) || (user?.roles.includes("ADMIN"))) && ( - + {user && (user.id === review.user.id || user.roles.includes("ADMIN")) && isEditing ? ( + <> + {reviewForm.errorMessage && ( +
+ + Error: + +

+ {reviewForm.errorMessage} +

+
)} + setIsEditing(false)} + /> + + ) : ( +
+
+ userImage +

{review.user.username}

+

{review.date}

+
+
+

{review.title}

+

{review.message}

+

Valoración del producto: {convertRatingToStars(review.rating)} {review.rating}/5

+ {((user?.id === review.user.id) || (user?.roles.includes("ADMIN"))) && ( + <> + + + + )} +
-
+ )} setIsDeleteModalOpen(false)}> diff --git a/frontend/app/components/reviewForm.tsx b/frontend/app/components/reviewForm.tsx index ed43ab1..4885e50 100644 --- a/frontend/app/components/reviewForm.tsx +++ b/frontend/app/components/reviewForm.tsx @@ -1,21 +1,26 @@ import type { SubmitEvent, RefObject } from "react"; import { FormControl, FormLabel, Button } from "react-bootstrap"; -import { Star } from "react-bootstrap-icons"; +import { Star, X } from "react-bootstrap-icons"; +import type ReviewDTO from "~/dtos/ReviewDTO"; interface ReviewFormProps { + review?: Partial onSubmit: (event: SubmitEvent) => void; isPending: boolean; wasValidated: boolean; formRef: RefObject; submitLabel?: string; + onCancel?: () => void; } -export default function ComponentForm({ +export default function ReviewForm({ + review, onSubmit, isPending, wasValidated, formRef, submitLabel, + onCancel }: Readonly) { return ( @@ -23,13 +28,14 @@ export default function ComponentForm({ ref={formRef} onSubmit={onSubmit} className={`custom-review-form needs-validation ${wasValidated ? "was-validated" : ""}`} + id={review ? 'edit-review-form' : 'create-review-form'} noValidate >

¡Añade una reseña a este producto!

Título: - +
Por favor, ingrese un título válido.
@@ -37,7 +43,7 @@ export default function ComponentForm({
Mensaje: - +
Por favor, ingrese un mensaje válido.
@@ -46,7 +52,7 @@ export default function ComponentForm({
Valoración:
- +
Por favor, ingrese una valoración válida.
@@ -54,10 +60,18 @@ export default function ComponentForm({
- +
+ {onCancel && ( + + )} + +
); } \ No newline at end of file diff --git a/frontend/app/hooks/use-review-form.ts b/frontend/app/hooks/use-review-form.ts new file mode 100644 index 0000000..662d5c2 --- /dev/null +++ b/frontend/app/hooks/use-review-form.ts @@ -0,0 +1,53 @@ +import { useActionState, useRef, useState } from "react"; +import type { SubmitEvent } from "react"; +import { getReviewFormValues } from "~/utils/review-form-utils"; +import type { ReviewFormValues } from "~/utils/review-form-utils"; +import { handleFormSubmit } from "~/utils/general-form-utils"; + +interface UseReviewFormProps { + initialState: ReviewFormValues; + submitAction: ( + values: ReviewFormValues + ) => Promise; + defaultErrorMessage: string; +} + +export function useReviewForm({ initialState, submitAction, defaultErrorMessage }: UseReviewFormProps) { + const [wasValidated, setWasValidated] = useState(false); + const [errorMessage, setErrorMessage] = useState(""); + + const formRef = useRef(null); + + async function action(_prevState: ReviewFormValues, formData: FormData): Promise { + const values = getReviewFormValues(formData); + + try { + setErrorMessage(""); + await submitAction(values); + } catch (error) { + console.error(error); + + setErrorMessage( + error instanceof Error + ? error.message + : defaultErrorMessage + ); + } + + return values; + } + + const [, formAction, isPending] = useActionState(action, initialState); + + function handleSubmit(event: SubmitEvent) { + handleFormSubmit(event, formAction, setWasValidated); + } + + return { + wasValidated, + errorMessage, + formRef, + isPending, + handleSubmit, + }; +} diff --git a/frontend/app/routes/components-create.tsx b/frontend/app/routes/components-create.tsx index 4b0c30b..789f9d9 100644 --- a/frontend/app/routes/components-create.tsx +++ b/frontend/app/routes/components-create.tsx @@ -40,7 +40,7 @@ export default function ComponentsCreate() {
- + Volver diff --git a/frontend/app/routes/components-update.tsx b/frontend/app/routes/components-update.tsx index eab821e..5c0050f 100644 --- a/frontend/app/routes/components-update.tsx +++ b/frontend/app/routes/components-update.tsx @@ -47,7 +47,7 @@ export default function ComponentsUpdate({ loaderData }: Route.ComponentProps) {
- + Volver diff --git a/frontend/app/routes/detail-component.tsx b/frontend/app/routes/detail-component.tsx index 42d1120..6d732f2 100644 --- a/frontend/app/routes/detail-component.tsx +++ b/frontend/app/routes/detail-component.tsx @@ -3,14 +3,14 @@ import { ArrowLeft, CartPlus, ExclamationCircleFill, Image as ImageIcon, PencilS import type { Route } from "./+types/detail-component"; import { deleteComponent, getComponent } from "~/services/components-service"; import { useUserStore } from "~/stores/user-store"; -import { useActionState, useEffect, useRef, useState, type SubmitEvent } from "react"; +import { useEffect, useState } from "react"; import { Link, useNavigate, useRevalidator } from "react-router"; import ReviewCard from "~/components/reviewCard"; import type ReviewDTO from "~/dtos/ReviewDTO"; import { createReview, getReviews, hasUserReviewed } from "~/services/reviews-service"; import ReviewForm from "~/components/reviewForm"; -import { getReviewFormValues, type ReviewFormValues } from "~/utils/review-form-utils"; -import { handleFormSubmit } from "~/utils/general-form-utils"; +import { type ReviewFormValues } from "~/utils/review-form-utils"; +import { useReviewForm } from "~/hooks/use-review-form"; const API_URL = "/api/v1/components"; @@ -42,13 +42,7 @@ export default function ComponentDetail({ loaderData }: Route.ComponentProps) { const [currentPage, setCurrentPage] = useState(1); const [isLoadingMore, setIsLoadingMore] = useState(false); const [loadMoreError, setLoadMoreError] = useState(false); - const [wasValidated, setWasValidated] = useState(false); - const formRef = useRef(null); - const [errorMessage, setErrorMessage] = useState(""); - const [, formAction, isPending] = useActionState( - createReviewAction, - { title: "", message: "", rating: 0 } - ); + useEffect(() => { setReviews(loaderData.reviews.items); @@ -90,29 +84,20 @@ export default function ComponentDetail({ loaderData }: Route.ComponentProps) { } }; - async function createReviewAction(_prevState: ReviewFormValues, formData: FormData) { - const { title, message, rating } = getReviewFormValues(formData); - setErrorMessage(""); + const initialState: ReviewFormValues = { + title: "", + message: "", + rating: 0, + }; - try { - await createReview(component.id, title, message, rating); + const reviewForm = useReviewForm({ + initialState, + submitAction: async (values) => { + await createReview(component.id, values.title, values.message, values.rating); await revalidator.revalidate(); - } catch (error) { - console.log(error); - - setErrorMessage( - error instanceof Error - ? error.message - : "Hubo un error al guardar la reseña. Por favor, inténtalo de nuevo.", - ); - } - - return { title, message, rating }; - } - - function handleSubmit(event: SubmitEvent) { - handleFormSubmit(event, formAction, setWasValidated); - } + }, + defaultErrorMessage: "Hubo un error al crear la reseña. Por favor, inténtalo de nuevo." + }); async function handleDeleteReview() { await revalidator.revalidate(); @@ -174,21 +159,21 @@ export default function ComponentDetail({ loaderData }: Route.ComponentProps) {
{user && !loaderData.hasReviewed && ( <> - {errorMessage && ( + {reviewForm.errorMessage && (
Error:

- {errorMessage} + {reviewForm.errorMessage}

)} diff --git a/frontend/app/routes/login.tsx b/frontend/app/routes/login.tsx index d6a9509..3c9c75f 100644 --- a/frontend/app/routes/login.tsx +++ b/frontend/app/routes/login.tsx @@ -103,8 +103,8 @@ export default function Login() {

¿No tiene cuenta en PCMod?

diff --git a/frontend/app/routes/register.tsx b/frontend/app/routes/register.tsx index a5c0cf3..1ad5b8c 100644 --- a/frontend/app/routes/register.tsx +++ b/frontend/app/routes/register.tsx @@ -126,8 +126,8 @@ export default function Register() {

¿Ya tiene cuenta en PCMod?

diff --git a/frontend/app/services/reviews-service.ts b/frontend/app/services/reviews-service.ts index fabecb5..24c2f32 100644 --- a/frontend/app/services/reviews-service.ts +++ b/frontend/app/services/reviews-service.ts @@ -97,4 +97,34 @@ export async function deleteReview(id: number, reviewId: number): Promise throw new Error("Error deleting review"); } +} + +export async function updateReview(componentId: number, reviewId: number, title: string, message: string, rating: number): Promise { + const url = new URL(`${API_URL}/${componentId}/reviews/${reviewId}`, getBaseUrl()); + const res = await fetch(url.toString(), { + method: 'PUT', + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + title, + message, + rating + }) + }); + + if (!res.ok) { + let message: string | undefined; + + try { + const error = await res.json(); + message = typeof error.message === "string" ? error.message : undefined; + } catch { + message = undefined; + } + + throw new Error(message ?? "There was an error while updating the review."); + } + + return await res.json(); } \ No newline at end of file diff --git a/frontend/tests/integration/ComponentDetailPage.integration.test.tsx b/frontend/tests/integration/ComponentDetailPage.integration.test.tsx index 47b18a4..d056d4c 100644 --- a/frontend/tests/integration/ComponentDetailPage.integration.test.tsx +++ b/frontend/tests/integration/ComponentDetailPage.integration.test.tsx @@ -1,4 +1,4 @@ -import { render, screen, waitFor } from "@testing-library/react"; +import { render, screen, waitFor, within } from "@testing-library/react"; import fetchCookie from "fetch-cookie"; import userEvent from "@testing-library/user-event"; import { createMemoryRouter, createRoutesStub, Navigate, RouterProvider } from "react-router"; @@ -318,7 +318,7 @@ describe("ComponentDetailPageIntegration", () => { }); - it("it does not show the review delete button for non-registered users", async () => { + it("it does not show the review delete and update buttons for non-registered users", async () => { const componentData = await clientLoader({ params: { id: "2" } } as Parameters[0]); @@ -335,13 +335,15 @@ describe("ComponentDetailPageIntegration", () => { render(); await waitFor(() => { + expect(document.getElementById("update-review-button-1")).not.toBeInTheDocument(); + expect(document.getElementById("update-review-button-2")).not.toBeInTheDocument(); expect(document.getElementById("delete-review-button-1")).not.toBeInTheDocument(); expect(document.getElementById("delete-review-button-2")).not.toBeInTheDocument(); }); }); - it("shows only the delete review button for logged-in non-admin users for own reviews", async () => { + it("shows only the delete and update review buttonw for logged-in non-admin users for own reviews", async () => { const user = userEvent.setup(); const RouterStub = createRoutesStub([ @@ -357,13 +359,15 @@ describe("ComponentDetailPageIntegration", () => { await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + expect(document.getElementById("update-review-button-2")).not.toBeInTheDocument(); expect(document.getElementById("delete-review-button-1")).toBeInTheDocument(); expect(document.getElementById("delete-review-button-2")).not.toBeInTheDocument(); }); }); - it("shows the review delete button for admin users for all reviews", async () => { + it("shows the review delete and update review buttons for admin users for all reviews", async () => { const user = userEvent.setup(); const RouterStub = createRoutesStub([ @@ -379,6 +383,8 @@ describe("ComponentDetailPageIntegration", () => { await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + expect(document.getElementById("update-review-button-2")).toBeInTheDocument(); expect(document.getElementById("delete-review-button-1")).toBeInTheDocument(); expect(document.getElementById("delete-review-button-2")).toBeInTheDocument(); }); @@ -740,4 +746,227 @@ describe("ComponentDetailPageIntegration", () => { }); + it("updates review as logged in user no admin", async () => { + + const user = userEvent.setup(); + const RouterStub = createRoutesStub([ + { path: "/login", Component: Login }, + { path: "/", Component: () => }, + { path: "/components/:id", Component: ComponentDetail, loader: clientLoader }, + ]); + + render(); + + await user.type(screen.getByLabelText("Correo electrónico:"), "user@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "userpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await waitFor(() => { + expect(document.getElementById("update-review-button-4")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-4")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "5"); + + const updateButton = await screen.findByRole("button", { name: /Actualizar reseña/i }); + await user.click(updateButton); + + await waitFor(() => { + expect(screen.getByText("sample_title")).toBeInTheDocument(); + expect(screen.getByText("sample_message")).toBeInTheDocument(); + expect(screen.getByText("Valoración del producto: ★★★★★ 5/5")).toBeInTheDocument(); + expect(screen.getByText(/5\/5 \(1 reseña\(s\)\)/i)).toBeInTheDocument(); + }); + + }); + + it("updates review as admin", async () => { + + const user = userEvent.setup(); + const RouterStub = createRoutesStub([ + { path: "/login", Component: Login }, + { path: "/", Component: () => }, + { path: "/components/:id", Component: ComponentDetail, loader: clientLoader }, + ]); + + render(); + + await user.type(screen.getByLabelText("Correo electrónico:"), "admin@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "adminpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await waitFor(() => { + expect(document.getElementById("update-review-button-4")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-4")!); + + const editForm = document.getElementById("edit-review-form")!; + + await user.clear(within(editForm).getByLabelText("Título:")); + await user.type(within(editForm).getByLabelText("Título:"), "sample_title_admin"); + await user.clear(within(editForm).getByLabelText("Mensaje:")); + await user.type(within(editForm).getByLabelText("Mensaje:"), "sample_message_admin"); + await user.clear(within(editForm).getByLabelText("Valoración:")); + await user.type(within(editForm).getByLabelText("Valoración:"), "4"); + + await user.click(within(editForm).getByRole("button", {name: /Actualizar reseña/i})); + + await waitFor(() => { + expect(screen.getByText("sample_title_admin")).toBeInTheDocument(); + expect(screen.getByText("sample_message_admin")).toBeInTheDocument(); + expect(screen.getByText("Valoración del producto: ★★★★☆ 4/5")).toBeInTheDocument(); + expect(screen.getByText(/4\/5 \(1 reseña\(s\)\)/i)).toBeInTheDocument(); + }); + + }); + + it("updates review with void data", async () => { + + const user = userEvent.setup(); + const RouterStub = createRoutesStub([ + { path: "/login", Component: Login }, + { path: "/", Component: () => }, + { path: "/components/:id", Component: ComponentDetail, loader: clientLoader }, + ]); + + render(); + + await user.type(screen.getByLabelText("Correo electrónico:"), "user@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "userpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await waitFor(() => { + expect(document.getElementById("update-review-button-4")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-4")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.clear(screen.getByLabelText("Valoración:")); + + const updateButton = await screen.findByRole("button", { name: /Actualizar reseña/i }); + await user.click(updateButton); + + expect(screen.getByText("Por favor, ingrese un título válido.")).toBeInTheDocument(); + expect(screen.getByText("Por favor, ingrese un mensaje válido.")).toBeInTheDocument(); + expect(screen.getByText("Por favor, ingrese una valoración válida.")).toBeInTheDocument(); + + }); + + it("updates review with invalid format data", async () => { + + const user = userEvent.setup(); + const RouterStub = createRoutesStub([ + { path: "/login", Component: Login }, + { path: "/", Component: () => }, + { path: "/components/:id", Component: ComponentDetail, loader: clientLoader }, + ]); + + render(); + + await user.type(screen.getByLabelText("Correo electrónico:"), "user@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "userpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await waitFor(() => { + expect(document.getElementById("update-review-button-4")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-4")!); + + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "-5"); + + const updateButton = await screen.findByRole("button", { name: /Actualizar reseña/i }); + await user.click(updateButton); + + expect(screen.getByText("Por favor, ingrese una valoración válida.")).toBeInTheDocument(); + + }); + + it("shows the backend error with message when updating a review fails", async () => { + const user = userEvent.setup(); + const backendErrorMessage = "sample_backend_error"; + const RouterStub = createRoutesStub([ + { path: "/login", Component: Login }, + { path: "/", Component: () => }, + { path: "/components/:id", Component: ComponentDetail, loader: clientLoader }, + ]); + + render(); + + await user.type(screen.getByLabelText("Correo electrónico:"), "user@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "userpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await waitFor(() => { + expect(document.getElementById("update-review-button-4")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-4")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "5"); + + vi.spyOn(globalThis, "fetch").mockImplementationOnce(() => Promise.resolve( + new Response( + JSON.stringify({ message: backendErrorMessage }), + { status: 400, headers: { "Content-Type": "application/json" } }, + ), + )); + + await user.click(screen.getByRole("button", { name: /Actualizar reseña/i })); + + await waitFor(() => { + expect(screen.getByText(backendErrorMessage)).toBeInTheDocument(); + }); + }); + + it("shows the backend error without message when updating a review fails", async () => { + const user = userEvent.setup(); + const RouterStub = createRoutesStub([ + { path: "/login", Component: Login }, + { path: "/", Component: () => }, + { path: "/components/:id", Component: ComponentDetail, loader: clientLoader }, + ]); + + render(); + + await user.type(screen.getByLabelText("Correo electrónico:"), "user@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "userpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await waitFor(() => { + expect(document.getElementById("update-review-button-4")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-4")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "5"); + + vi.spyOn(globalThis, "fetch").mockImplementationOnce(() => Promise.resolve( + new Response( + JSON.stringify({ }), + { status: 400, headers: { "Content-Type": "application/json" } }, + ), + )); + + await user.click(screen.getByRole("button", { name: /Actualizar reseña/i })); + + await waitFor(() => { + expect(screen.getByText("There was an error while updating the review.")).toBeInTheDocument(); + }); + }); + }); \ No newline at end of file diff --git a/frontend/tests/unit/ComponentDetailPage.test.tsx b/frontend/tests/unit/ComponentDetailPage.test.tsx index 4289188..fc21ded 100644 --- a/frontend/tests/unit/ComponentDetailPage.test.tsx +++ b/frontend/tests/unit/ComponentDetailPage.test.tsx @@ -4,7 +4,7 @@ import "@testing-library/jest-dom"; import { createMemoryRouter, createRoutesStub, RouterProvider } from "react-router"; import ComponentDetail, { clientLoader } from "~/routes/detail-component"; import { getComponent, deleteComponent, getComponents } from "~/services/components-service"; -import { createReview, deleteReview, getReviews, hasUserReviewed } from "~/services/reviews-service"; +import { createReview, deleteReview, getReviews, hasUserReviewed, updateReview } from "~/services/reviews-service"; import { reqIsLogged, getPublicUser } from "~/services/users-service"; import { useUserStore } from "~/stores/user-store"; import userEvent from "@testing-library/user-event"; @@ -19,6 +19,7 @@ vi.mock("~/services/reviews-service", () => ({ getReviews: vi.fn(), createReview: vi.fn(), deleteReview: vi.fn(), + updateReview: vi.fn(), hasUserReviewed: vi.fn(), })); @@ -786,7 +787,7 @@ describe("ComponentDetailPage", () => { }); - it("throws the default error when the createReview request fails with a backend message", async () => { + it("throws the default error when the createReview request fails without a backend message", async () => { const user = userEvent.setup(); vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); @@ -822,7 +823,7 @@ describe("ComponentDetailPage", () => { }); - it("it does not show the review delete button for non-registered users", async () => { + it("it does not show the review delete and update buttons for non-registered users", async () => { const RouterStub = createRoutesStub([ { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component2, reviews: { items: [review1, review2], hasNext: false } }) }, @@ -831,13 +832,15 @@ describe("ComponentDetailPage", () => { render(); await waitFor(() => { + expect(document.getElementById("update-review-button-1")).not.toBeInTheDocument(); + expect(document.getElementById("update-review-button-2")).not.toBeInTheDocument(); expect(document.getElementById("delete-review-button-1")).not.toBeInTheDocument(); expect(document.getElementById("delete-review-button-2")).not.toBeInTheDocument(); }); }); - it("shows only the delete review button for logged-in non-admin users for own reviews", async () => { + it("shows only the delete and update review buttons for logged-in non-admin users for own reviews", async () => { const RouterStub = createRoutesStub([ { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component2, reviews: { items: [review1, review2], hasNext: false } }) }, @@ -849,13 +852,15 @@ describe("ComponentDetailPage", () => { render(); await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + expect(document.getElementById("delete-review-button-2")).not.toBeInTheDocument(); expect(document.getElementById("delete-review-button-1")).toBeInTheDocument(); expect(document.getElementById("delete-review-button-2")).not.toBeInTheDocument(); }); }); - it("shows the review delete button for admin users for all reviews", async () => { + it("shows the review delete and update buttons for admin users for all reviews", async () => { const RouterStub = createRoutesStub([ { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component2, reviews: { items: [review1, review2], hasNext: false } }) }, @@ -867,6 +872,8 @@ describe("ComponentDetailPage", () => { render(); await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + expect(document.getElementById("update-review-button-2")).toBeInTheDocument(); expect(document.getElementById("delete-review-button-1")).toBeInTheDocument(); expect(document.getElementById("delete-review-button-2")).toBeInTheDocument(); }); @@ -965,4 +972,347 @@ describe("ComponentDetailPage", () => { }); }); + it("updates a review with valid data as logged in no admin user", async () => { + + const user = userEvent.setup(); + let updatedReview = review1; + + vi.mocked(reqIsLogged).mockResolvedValue(userAccount); + useUserStore.setState({ user: userAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(true); + vi.mocked(updateReview).mockImplementation(async () => { + updatedReview = { + ...review1, + title: "sample_title_updated", + message: "sample_message_updated", + rating: 3, + }; + + return updatedReview; + }); + + const RouterStub = createRoutesStub([ + { + path: "/components/:id", + Component: ComponentDetail, + loader: () => ({ + component: component2, + reviews: { + items: [updatedReview], + hasNext: false + }, + hasReviewed: true + }) + }, + ]); + + render(); + + await screen.findByText("Intel Core i5-12400F"); + + await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-1")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title_updated"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message_updated"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "3"); + + const updateButton = await screen.findByRole("button", { name: /Actualizar reseña/i }); + await user.click(updateButton); + + await waitFor(() => { + expect(updateReview).toHaveBeenCalledTimes(1); + expect(screen.getByText("sample_title_updated")).toBeInTheDocument(); + expect(screen.getByText("sample_message_updated")).toBeInTheDocument(); + expect(screen.getByText("Valoración del producto: ★★★☆☆ 3/5")).toBeInTheDocument(); + }); + + }); + + it("updates a review with valid data as admin", async () => { + + const user = userEvent.setup(); + + let updatedReview = review1; + + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(true); + vi.mocked(updateReview).mockImplementation(async () => { + updatedReview = { + ...review1, + title: "sample_title_updated", + message: "sample_message_updated", + rating: 3, + }; + + return updatedReview; + }); + + const RouterStub = createRoutesStub([ + { + path: "/components/:id", + Component: ComponentDetail, + loader: () => ({ + component: component2, + reviews: { + items: [updatedReview], + hasNext: false + }, + hasReviewed: true + }) + }, + ]); + + render(); + + await screen.findByText("Intel Core i5-12400F"); + + await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-1")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title_updated"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message_updated"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "3"); + + const updateButton = await screen.findByRole("button", { name: /Actualizar reseña/i }); + await user.click(updateButton); + + await waitFor(() => { + expect(updateReview).toHaveBeenCalledTimes(1); + expect(screen.getByText("sample_title_updated")).toBeInTheDocument(); + expect(screen.getByText("sample_message_updated")).toBeInTheDocument(); + expect(screen.getByText("Valoración del producto: ★★★☆☆ 3/5")).toBeInTheDocument(); + }); + + }); + + it("cancel update of a review", async () => { + + const user = userEvent.setup(); + let updatedReview = review1; + + vi.mocked(reqIsLogged).mockResolvedValue(userAccount); + useUserStore.setState({ user: userAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(true); + + const RouterStub = createRoutesStub([ + { + path: "/components/:id", + Component: ComponentDetail, + loader: () => ({ + component: component2, + reviews: { + items: [review1], + hasNext: false + }, + hasReviewed: true + }) + }, + ]); + + render(); + + await screen.findByText("Intel Core i5-12400F"); + + await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-1")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title_updated"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message_updated"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "3"); + + const cancelButton = await screen.findByRole("button", { name: /Cancelar/i }); + await user.click(cancelButton); + + await waitFor(() => { + expect(screen.queryByText("sample_title_updated")).not.toBeInTheDocument(); + expect(screen.queryByText("sample_message_updated")).not.toBeInTheDocument(); + expect(screen.queryByText("Valoración del producto: ★★★☆☆ 3/5")).not.toBeInTheDocument(); + }); + + }); + + it("show error when updating a review with void data", async () => { + + const user = userEvent.setup(); + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(true); + + const RouterStub = createRoutesStub([ + { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component2, reviews: { items: [review1], hasNext: false }, hasReviewed: true }) }, + ]); + + render(); + + await screen.findByText("Intel Core i5-12400F"); + + await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-1")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.clear(screen.getByLabelText("Valoración:")); + + const updateButton = await screen.findByRole("button", { name: /Actualizar reseña/i }); + await user.click(updateButton); + + await waitFor(() => { + expect(updateReview).not.toHaveBeenCalled(); + expect(screen.getByText("Por favor, ingrese un título válido.")).toBeInTheDocument(); + expect(screen.getByText("Por favor, ingrese un mensaje válido.")).toBeInTheDocument(); + expect(screen.getByText("Por favor, ingrese una valoración válida.")).toBeInTheDocument(); + }); + + }); + + it("show error when updating a review with invalid data", async () => { + + const user = userEvent.setup(); + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(true); + + const RouterStub = createRoutesStub([ + { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component2, reviews: { items: [review1], hasNext: false }, hasReviewed: true }) }, + ]); + + render(); + + await screen.findByText("Intel Core i5-12400F"); + + await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-1")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title_updated"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message_updated"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "-3"); + + const updateButton = await screen.findByRole("button", { name: /Actualizar reseña/i }); + await user.click(updateButton); + + await waitFor(() => { + expect(updateReview).not.toHaveBeenCalled(); + expect(screen.getByText("Por favor, ingrese una valoración válida.")).toBeInTheDocument(); + }); + + }); + + it("throws an error when the updateReview request fails with a backend message", async () => { + const user = userEvent.setup(); + const backendErrorMessage = "sample_error_message"; + + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + vi.mocked(hasUserReviewed).mockResolvedValue(true); + vi.mocked(updateReview).mockRejectedValue(new Error(backendErrorMessage)); + + const RouterStub = createRoutesStub([ + { + path: "/components/:id", + Component: ComponentDetail, + loader: () => ({ + component: component2, + reviews: { items: [review1], hasNext: false }, + hasReviewed: true, + }), + }, + ]); + + render(); + + await screen.findByText("Intel Core i5-12400F"); + + await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-1")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title_updated"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message_updated"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "5"); + await user.click(screen.getByRole("button", { name: /Actualizar reseña/i })); + + await waitFor(() => { + expect(updateReview).toHaveBeenCalledWith(2, 1, "sample_title_updated", "sample_message_updated", 5); + expect(screen.getByText(backendErrorMessage)).toBeInTheDocument(); + }); + + }); + + it("throws the default error when the updateReview request fails without a backend message", async () => { + const user = userEvent.setup(); + + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + vi.mocked(hasUserReviewed).mockResolvedValue(true); + vi.mocked(updateReview).mockRejectedValue(new Error("There was an error while updating the review.")); + + const RouterStub = createRoutesStub([ + { + path: "/components/:id", + Component: ComponentDetail, + loader: () => ({ + component: component2, + reviews: { items: [review1], hasNext: false }, + hasReviewed: true, + }), + }, + ]); + + render(); + + await screen.findByText("Intel Core i5-12400F"); + + await waitFor(() => { + expect(document.getElementById("update-review-button-1")).toBeInTheDocument(); + }); + await user.click(document.getElementById("update-review-button-1")!); + + await user.clear(screen.getByLabelText("Título:")); + await user.type(screen.getByLabelText("Título:"), "sample_title_updated"); + await user.clear(screen.getByLabelText("Mensaje:")); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message_updated"); + await user.clear(screen.getByLabelText("Valoración:")); + await user.type(screen.getByLabelText("Valoración:"), "5"); + await user.click(screen.getByRole("button", { name: /Actualizar reseña/i })); + + await waitFor(() => { + expect(updateReview).toHaveBeenCalledWith(2, 1, "sample_title_updated", "sample_message_updated", 5); + expect(screen.getByText("There was an error while updating the review.")).toBeInTheDocument(); + }); + + }); + }); \ No newline at end of file