From 676cfd5135c59dffb47bd3ac46c94ba394dfd9e7 Mon Sep 17 00:00:00 2001 From: jaimeeg5 Date: Tue, 10 Nov 2026 20:35:27 +0100 Subject: [PATCH 1/3] feat: add review creation backend and tests --- .../controller/ReviewsRestController.java | 21 ++ .../pcmod/repository/ReviewsRepository.java | 2 + .../pcmod/security/SecurityConfig.java | 1 + .../pcmod/service/ReviewsService.java | 64 +++++ .../pcmod/e2e/api/ComponentsSystemTests.java | 2 + .../pcmod/e2e/api/HomePageSystemTests.java | 2 + .../pcmod/e2e/api/ReviewsSystemTests.java | 226 ++++++++++++++++-- .../integration/ReviewsIntegrationTests.java | 221 ++++++++++++++++- .../pcmod/unit/ReviewsUnitTests.java | 188 +++++++++++++++ 9 files changed, 701 insertions(+), 26 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 16adef9..591f60e 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,15 +1,24 @@ package es.codeurjcstudents.pcmod.controller; +import java.net.URI; +import java.security.Principal; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; 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.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; @RestController @@ -24,6 +33,18 @@ public Page findAllByComponent(@PathVariable long id, Pageable pageab return reviewsService.findAllByComponent(id, pageable).map(reviewsService::toDTO); } + @PostMapping("/") + public ResponseEntity createReview(@RequestBody ReviewDTO reviewDTO, @PathVariable long id, Principal principal) { + + Review review = reviewsService.toDomain(reviewDTO); + + reviewsService.save(review, Long.valueOf(principal.getName()), id); + + URI location = fromCurrentRequest().path("/{id}").buildAndExpand(review.getId()).toUri(); + + return ResponseEntity.created(location).body(reviewsService.toDTO(review)); + } + @DeleteMapping("/{reviewId}") public void deleteReview(@PathVariable long id, @PathVariable long reviewId) { reviewsService.delete(id, reviewId); diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/repository/ReviewsRepository.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/repository/ReviewsRepository.java index 0b71997..4c89229 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/repository/ReviewsRepository.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/repository/ReviewsRepository.java @@ -10,4 +10,6 @@ public interface ReviewsRepository extends JpaRepository { Page findAllByComponentId(Long id, Pageable pageable); + boolean existsByComponentIdAndUserId(Long componentId, Long userId); + } \ No newline at end of file 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 8737b6b..237268b 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 @@ -59,6 +59,7 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) { .exceptionHandling(handling -> handling.authenticationEntryPoint(unauthorizedHandlerJwt)); 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.GET, "/api/v1/users/me").hasRole("REGISTERED_USER") .requestMatchers(HttpMethod.POST, "/api/v1/users/*/image").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 f0a3aa2..856a20a 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 @@ -1,5 +1,9 @@ package es.codeurjcstudents.pcmod.service; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; @@ -55,6 +59,66 @@ public Page findAllByComponent(long id, Pageable pageable) { return reviewRepository.findAllByComponentId(id, pageable); } + @PreAuthorize("hasRole('REGISTERED_USER') and (#userId.toString() == principal.username)") + @Transactional + public Review save(Review review, long userId, long componentId) { + + if (reviewRepository.existsByComponentIdAndUserId(componentId, userId)) { + throw new IllegalArgumentException("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario."); + } + + List errors = validateReview(review); + + if (!errors.isEmpty()) { + throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + } + + User user = userRepository.findById(userId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado.")); + + Component component = componentRepository.findById(componentId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Componente no encontrado.")); + + review.setDate(LocalDate.now(ZoneId.of("Europe/Madrid"))); + user.addReview(review); + component.addReview(review); + + return reviewRepository.save(review); + } + + public List validateReview(Review review) { + + List errors = new ArrayList<>(); + + validateRequiredField(review.getTitle(), "El título es obligatorio.", errors); + validateRequiredField(review.getMessage(), "El mensaje es obligatorio.", errors); + + if (review.getRating() == null || review.getRating().toString().isEmpty()) { + errors.add("La valoración es obligatoria."); + } else { + validateRating(review, errors); + } + + return errors; + + } + + private void validateRequiredField(String value, String message, List errors) { + + if (value == null || value.isEmpty()) { + errors.add(message); + } + + } + + public void validateRating(Review review, List errors) { + + if ((review.getRating() < 1) || (review.getRating() > 5)) { + errors.add("La valoración del producto ha de estar entre 1 y 5."); + } + + } + @PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)") public void delete(long componentId, long reviewId) { diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java index 3679867..7bdbf97 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java @@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.annotation.DirtiesContext; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; @@ -16,6 +17,7 @@ import java.io.InputStream; @Tag("server-system") +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class ComponentsSystemTests { diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/HomePageSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/HomePageSystemTests.java index 4c546f0..4ee9f6b 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/HomePageSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/HomePageSystemTests.java @@ -7,12 +7,14 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.annotation.DirtiesContext; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; @Tag("server-system") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class HomePageSystemTests { @LocalServerPort 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 81629f3..281a76a 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 @@ -4,12 +4,12 @@ import io.restassured.http.ContentType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.test.annotation.DirtiesContext; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; @@ -17,6 +17,7 @@ @Tag("server-system") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class ReviewsSystemTests { @LocalServerPort @@ -31,7 +32,6 @@ public void setup() { } @Test - @Order(1) public void getReviewsByComponentId() { given().header("Content-Type", "application/json") .when().get("components/2/reviews/") @@ -48,7 +48,6 @@ public void getReviewsByComponentId() { } @Test - @Order(2) public void getZeroReviewsByComponentId() { given().header("Content-Type", "application/json") .when().get("components/1/reviews/") @@ -60,7 +59,206 @@ public void getZeroReviewsByComponentId() { } @Test - @Order(3) + public void postReviewAsNoLoggedIn() { + given() + .header("Content-Type", "application/json") + .body(""" + { + "title": "sample_title", + "message": "sample_message", + "rating": 5 + } + """) + .when().post("/components/5/reviews/") + .then().statusCode(401).contentType(ContentType.JSON) + .body("error", equalTo("Unauthorized")); + } + + @Test + public void postReviewAsRegisteredUserNoAdmin() { + 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().post("/components/5/reviews/") + .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 postReviewAsAdmin() { + 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().post("/components/5/reviews/") + .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 postReviewForAnExistingOwnReviewComponent() { + 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().post("/components/4/reviews/") + .then().statusCode(500).contentType(ContentType.JSON) + .body("message", equalTo("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.")); + } + + @Test + public void postVoidReviewData() { + 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().post("/components/5/reviews/") + .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 postNullComponentData() { + 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().post("/components/5/reviews/") + .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 postBadNumReviewData() { + 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().post("/components/5/reviews/") + .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.")); + } + + @Test public void deleteReviewAsNotLoggedIn() { given() @@ -71,7 +269,6 @@ public void deleteReviewAsNotLoggedIn() { } @Test - @Order(4) public void deleteOwnReview() { given().header("Content-Type", "application/json") @@ -105,7 +302,6 @@ public void deleteOwnReview() { } @Test - @Order(5) public void deleteOtherReviewAsNoAdmin() { String authToken = given() .header("Content-Type", "application/json") @@ -128,18 +324,12 @@ public void deleteOtherReviewAsNoAdmin() { } @Test - @Order(6) public void deleteReviewsAsAdmin() { given().header("Content-Type", "application/json") .when().get("components/2/reviews/") .then().statusCode(200).contentType(ContentType.JSON) - .body("totalElements", equalTo(1)); - - given().header("Content-Type", "application/json") - .when().get("components/3/reviews/") - .then().statusCode(200).contentType(ContentType.JSON) - .body("totalElements", equalTo(1)); + .body("totalElements", equalTo(2)); String authToken = given() .header("Content-Type", "application/json") @@ -156,13 +346,13 @@ public void deleteReviewsAsAdmin() { given() .header("Content-Type", "application/json") .cookie("AuthToken", authToken) - .when().delete("components/2/reviews/2") + .when().delete("components/2/reviews/1") .then().statusCode(200); given() .header("Content-Type", "application/json") .cookie("AuthToken", authToken) - .when().delete("components/3/reviews/3") + .when().delete("components/2/reviews/2") .then().statusCode(200); given().header("Content-Type", "application/json") @@ -170,15 +360,9 @@ public void deleteReviewsAsAdmin() { .then().statusCode(200).contentType(ContentType.JSON) .body("totalElements", equalTo(0)); - given().header("Content-Type", "application/json") - .when().get("components/3/reviews/") - .then().statusCode(200).contentType(ContentType.JSON) - .body("totalElements", equalTo(0)); - } @Test - @Order(7) public void deleteReviewWithWrongComponentId() { String authToken = given() 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 2ff9065..ea8d2a6 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 @@ -1,15 +1,15 @@ package es.codeurjcstudents.pcmod.integration; -import static org.junit.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.math.BigDecimal; import java.util.List; import java.util.NoSuchElementException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.springframework.beans.factory.annotation.Autowired; @@ -76,7 +76,10 @@ static void configureProperties(DynamicPropertyRegistry registry) { @BeforeEach void setUp() { + reviewsRepository.deleteAll(); componentsRepository.deleteAll(); + usersRepository.deleteAll(); + componentsRepository.save(new Component("AMD Ryzen 7 7800X3D", "8 núcleos y 16 hilos ideales para gaming", ComponentType.CPU, "AMD", BigDecimal.valueOf(350.00), 5)); @@ -85,13 +88,11 @@ void setUp() { ComponentType.STORAGE, "Kingston", BigDecimal.valueOf(100.00), 10)); SecurityContextHolder.clearContext(); - usersRepository.deleteAll(); usersRepository.save(new User("user1", "test", "userTest1", "c/testaddress", "testuser1@example.com", passwordEncoder.encode("pass"), "REGISTERED_USER")); usersRepository.save(new User("admin", "test", "adminTest1", "c/testaddress", "testadmin1@example.com", passwordEncoder.encode("adminpass"), "REGISTERED_USER", "ADMIN")); - reviewsRepository.deleteAll(); Review review1 = new Review("Buen procesador.", "Buen procesador para gaming.", 5); @@ -162,6 +163,216 @@ void testGetZeroReviews() { } + @Test + void postReviewAsNoRegisteredUser() { + Review review = new Review("sample_title", "sample_message", 5); + assertThrows(AuthenticationCredentialsNotFoundException.class, () -> reviewsService.save(review, usersRepository.findAll().getFirst().getId(), componentsRepository.findAll().getLast().getId())); + assertEquals(2, reviewsRepository.count()); + } + + @Test + void postReviewAsNoAdmin() { + 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 review = new Review("sample_title", "sample_message", 5); + assertDoesNotThrow(() -> reviewsService.save(review, user.getId(), componentsRepository.findAll().getLast().getId())); + assertEquals(3, reviewsRepository.count()); + } + + @Test + void postReviewAsAdmin() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("sample_title", "sample_message", 5); + assertDoesNotThrow(() -> reviewsService.save(review, admin.getId(), componentsRepository.findAll().getLast().getId())); + assertEquals(3, reviewsRepository.count()); + + } + + @Test + void postReviewInAComponentWithOwnReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("sample_title", "sample_message", 5); + assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), componentsRepository.findAll().getFirst().getId())); + assertEquals(2, reviewsRepository.count()); + + } + + @Test + void saveReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("sample_title", "sample_message", 5); + Component component = componentsRepository.findAll().getLast(); + Review savedReview = reviewsService.save(review, admin.getId(), component.getId()); + + assertEquals(review.getTitle(), savedReview.getTitle()); + assertEquals(review.getMessage(), savedReview.getMessage()); + assertEquals(review.getRating(), savedReview.getRating()); + assertEquals(component.getId(), savedReview.getComponent().getId()); + assertEquals(admin.getId(), savedReview.getUser().getId()); + assertEquals(3, reviewsRepository.count()); + + } + + @Test + void saveVoidReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("","", null); + Component component = componentsRepository.findAll().getLast(); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); + assertEquals(2, reviewsRepository.count()); + } + + @Test + void saveNullReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review(null,null, null); + Component component = componentsRepository.findAll().getLast(); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); + assertEquals(2, reviewsRepository.count()); + } + + @Test + void saveBadFormatReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("sample_title", "sample_message", -5); + Component component = componentsRepository.findAll().getLast(); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); + assertEquals(2, reviewsRepository.count()); + } + + @Test + void validateReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("sample_title", "sample_message", 5); + + List errors = reviewsService.validateReview(review); + + assertTrue(errors.isEmpty()); + + } + + @Test + void validateReviewInAComponentWithOwnReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("sample_title","sample_message", 5); + Component component = componentsRepository.findAll().getFirst(); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); + assertEquals("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.", exception.getMessage()); + assertEquals(2, reviewsRepository.count()); + } + + @Test + void validateVoidReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("", "", null); + + List errors = reviewsService.validateReview(review); + + assertTrue(errors.contains("El título es obligatorio.")); + assertTrue(errors.contains("El mensaje es obligatorio.")); + assertTrue(errors.contains("La valoración es obligatoria.")); + + } + + @Test + void validateNullReview() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review(null, null, null); + + List errors = reviewsService.validateReview(review); + + assertTrue(errors.contains("El título es obligatorio.")); + assertTrue(errors.contains("El mensaje es obligatorio.")); + assertTrue(errors.contains("La valoración es obligatoria.")); + + } + + @Test + void validateBadNumReviewData() { + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Review review = new Review("sample_title", "sample_message", -5); + + List errors = reviewsService.validateReview(review); + + assertTrue(errors.contains("La valoración del producto ha de estar entre 1 y 5.")); + + } + @Test void deleteReviewAsNotLoggedIn() { @@ -243,7 +454,7 @@ void deleteReviewOfWrongComponent() { Review review = reviewsRepository.findAll().getFirst(); assertThrows(NoSuchElementException.class, () -> reviewsService.delete(component.getId(), review.getId())); - assertEquals(0, reviewsRepository.count()); + assertEquals(2, reviewsRepository.count()); } 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 a5cefab..43f488a 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 @@ -151,6 +151,194 @@ void testGetZeroReviews() { verify(reviewsRepository).findAllByComponentId(1L, pageable); } + @Test + public void testSaveReview() { + + 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); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(reviewsRepository.existsByComponentIdAndUserId(1L, 1L)).thenReturn(false); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + + reviewsService.save(review, 1L, 1L); + + verify(reviewsRepository).save(any(Review.class)); + } + + @Test + public void testSaveReviewInComponentExistingSameUserReview() { + + 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); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(reviewsRepository.existsByComponentIdAndUserId(1L, 1L)).thenReturn(true); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, 1L, 1L)); + assertEquals("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.", exception.getMessage()); + verify(reviewsRepository, never()).save(any(Review.class)); + } + + @Test + public void testSaveVoidReviewData() { + + 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); + + User user = new User("user", "test", "userTest", "c/testaddress", "testuser@example.com", + passwordEncoder.encode("pass"), "REGISTERED_USER"); + + Review review = new Review("", "", null); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(reviewsRepository.existsByComponentIdAndUserId(1L, 1L)).thenReturn(false); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, 1L, 1L)); + verify(reviewsRepository, never()).save(any(Review.class)); + + } + + @Test + public void testSaveNullReviewData() { + + 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); + + User user = new User("user", "test", "userTest", "c/testaddress", "testuser@example.com", + passwordEncoder.encode("pass"), "REGISTERED_USER"); + + Review review = new Review(null, null, null); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(reviewsRepository.existsByComponentIdAndUserId(1L, 1L)).thenReturn(false); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, 1L, 1L)); + verify(reviewsRepository, never()).save(any(Review.class)); + + } + + @Test + public void testSaveBadNumReviewData() { + + 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); + + 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); + + when(componentsRepository.findById(1L)).thenReturn(Optional.of(component)); + when(reviewsRepository.existsByComponentIdAndUserId(1L, 1L)).thenReturn(false); + when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); + when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + + assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, 1L, 1L)); + verify(reviewsRepository, never()).save(any(Review.class)); + + } + + @Test + public void testReviewValidation() { + + ReviewsService reviewsService = new ReviewsService(null, null, null, null ); + + Review review = new Review("sample_title", "sample_message", 5); + + List errors = reviewsService.validateReview(review); + + assertTrue(errors.isEmpty()); + + } + + @Test + public void testVoidReviewValidation() { + + ReviewsService reviewsService = new ReviewsService(null, null, null, null ); + + Review review = new Review("", "", null); + + List errors = reviewsService.validateReview(review); + + assertTrue(errors.contains("El título es obligatorio.")); + assertTrue(errors.contains("El mensaje es obligatorio.")); + assertTrue(errors.contains("La valoración es obligatoria.")); + + } + + @Test + public void testNullReviewValidation() { + + ReviewsService reviewsService = new ReviewsService(null, null, null, null ); + + Review review = new Review(null, null, null); + + List errors = reviewsService.validateReview(review); + + assertTrue(errors.contains("El título es obligatorio.")); + assertTrue(errors.contains("El mensaje es obligatorio.")); + assertTrue(errors.contains("La valoración es obligatoria.")); + + } + + @Test + public void testBadNumReviewValidation() { + + ReviewsService reviewsService = new ReviewsService(null, null, null, null ); + + Review review = new Review("sample_title", "sample_message", -5); + + List errors = reviewsService.validateReview(review); + + assertTrue(errors.contains("La valoración del producto ha de estar entre 1 y 5.")); + + } + @Test public void testDeleteReview() { From f7d16b74a59e4bb17ee7e0a3fd77c2e6e8c72897 Mon Sep 17 00:00:00 2001 From: jaimeeg5 Date: Wed, 11 Nov 2026 20:36:29 +0100 Subject: [PATCH 2/3] feat: add review creation frontend and tests --- .../controller/ReviewsRestController.java | 10 + .../pcmod/service/ReviewsService.java | 4 + .../pcmod/e2e/api/ReviewsSystemTests.java | 50 +++++ .../pcmod/e2e/ui/ReviewsSystemTests.java | 127 ++++++++++- .../integration/ReviewsIntegrationTests.java | 32 +++ .../pcmod/unit/ReviewsUnitTests.java | 36 +++- frontend/app/app.css | 65 ++++++ frontend/app/components/reviewForm.tsx | 63 ++++++ frontend/app/routes/detail-component.tsx | 64 +++++- frontend/app/services/reviews-service.ts | 50 +++++ frontend/app/utils/review-form-utils.ts | 15 ++ .../ComponentDetailPage.integration.test.tsx | 148 +++++++++++++ .../tests/unit/ComponentDetailPage.test.tsx | 200 +++++++++++++++++- 13 files changed, 853 insertions(+), 11 deletions(-) create mode 100644 frontend/app/components/reviewForm.tsx create mode 100644 frontend/app/utils/review-form-utils.ts 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 591f60e..0bdf33e 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 @@ -33,6 +33,16 @@ public Page findAllByComponent(@PathVariable long id, Pageable pageab return reviewsService.findAllByComponent(id, pageable).map(reviewsService::toDTO); } + @GetMapping("/has-reviewed") + public ResponseEntity hasUserReviewed(@PathVariable long id, Principal principal) { + + if (principal == null) { + return ResponseEntity.ok(false); + } + + return ResponseEntity.ok(reviewsService.hasUserReviewed(id, Long.parseLong(principal.getName()))); + } + @PostMapping("/") public ResponseEntity createReview(@RequestBody ReviewDTO reviewDTO, @PathVariable long id, Principal principal) { 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 856a20a..d48e39d 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,10 @@ public Review save(Review review, long userId, long componentId) { return reviewRepository.save(review); } + public boolean hasUserReviewed(Long componentId, Long userId) { + return reviewRepository.existsByComponentIdAndUserId(componentId, userId); + } + public List validateReview(Review review) { List errors = new ArrayList<>(); 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 281a76a..2d62848 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 @@ -258,6 +258,56 @@ public void postBadNumReviewData() { "Validación fallida:\n• La valoración del producto ha de estar entre 1 y 5.")); } + @Test + public void hasReviewed() { + 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) + .when().get("/components/2/reviews/has-reviewed") + .then().statusCode(200).contentType(ContentType.JSON) + .body(equalTo("true")); + } + + @Test + public void hasNotReviewed() { + 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) + .when().get("/components/3/reviews/has-reviewed") + .then().statusCode(200).contentType(ContentType.JSON) + .body(equalTo("false")); + } + + @Test + public void hasReviewedWithNullUser() { + given() + .when().get("/components/2/reviews/has-reviewed") + .then().statusCode(200).contentType(ContentType.JSON) + .body(equalTo("false")); + } + @Test public void deleteReviewAsNotLoggedIn() { 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 cebe995..c8043c6 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 @@ -128,13 +128,14 @@ public void reviewsOptionsAsNonLoggedInTest() { driver.get("http://localhost:5173/components/2"); + assertThat(driver.findElements(By.id("save-review-button"))).isEmpty(); assertThat(driver.findElements(By.id("delete-review-button-1"))).isEmpty(); assertThat(driver.findElements(By.id("delete-review-button-2"))).isEmpty(); } @Test - public void reviewsOptionsAsLoggedInNoAdminTest() { + public void reviewsOptionsAsLoggedInNoAdminWithReviewTest() { login("user@example.com", "userpass"); @@ -144,13 +145,29 @@ public void reviewsOptionsAsLoggedInNoAdminTest() { wait.until(ExpectedConditions.presenceOfElementLocated(By.id("delete-review-button-1"))); + assertThat(driver.findElements(By.id("save-review-button"))).isEmpty(); assertThat(driver.findElements(By.id("delete-review-button-1"))).isNotEmpty(); assertThat(driver.findElements(By.id("delete-review-button-2"))).isEmpty(); } @Test - public void reviewsOptionsAsAdminTest() { + public void reviewsOptionsAsLoggedInWithoutReviewTest() { + + login("user@example.com", "userpass"); + + wait.until(ExpectedConditions.urlToBe("http://localhost:5173/")); + + driver.get("http://localhost:5173/components/1"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("save-review-button"))); + + assertThat(driver.findElements(By.id("save-review-button"))).isNotEmpty(); + + } + + @Test + public void reviewsOptionsAsAdminWithReviewTest() { login("admin@example.com", "adminpass"); @@ -159,11 +176,117 @@ public void reviewsOptionsAsAdminTest() { 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("delete-review-button-1"))).isNotEmpty(); assertThat(driver.findElements(By.id("delete-review-button-2"))).isNotEmpty(); } + @Test + public void reviewCreateRenderTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/1"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-heading"))); + String reviewHeading = driver.findElement(By.id("review-heading")).getText(); + assertThat(reviewHeading).isEqualTo("¡Añade una reseña a este producto!"); + + assertThat(driver.findElements(By.id("error-message"))).isEmpty(); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-title-tag"))); + assertThat(driver.findElement(By.id("review-title-tag")).getText()).isEqualTo("Título:"); + assertThat(driver.findElement(By.id("invalid-title")).isDisplayed()).isFalse(); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("message-title"))); + assertThat(driver.findElement(By.id("message-title")).getText()).isEqualTo("Mensaje:"); + assertThat(driver.findElement(By.id("invalid-message")).isDisplayed()).isFalse(); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("rating-title"))); + assertThat(driver.findElement(By.id("rating-title")).getText()).isEqualTo("Valoración:"); + assertThat(driver.findElement(By.id("invalid-rating")).isDisplayed()).isFalse(); + + assertThat(driver.findElements(By.name("save-review-button"))).isNotEmpty(); + + } + + @Test + public void createReviewTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/5"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("title"))); + driver.findElement(By.id("title")).sendKeys("sample_title"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("message"))); + driver.findElement(By.id("message")).sendKeys("sample_message"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("rating"))); + driver.findElement(By.id("rating")).sendKeys("5"); + + scrollToAndClick(By.name("save-review-button")); + + driver.get("http://localhost:5173/components/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: ★★★★★ 5/5 (1 reseña(s))"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("usernameReview-2"))); + String savedUserReview = driver.findElement(By.id("usernameReview-2")).getText(); + assertThat(savedUserReview).isEqualTo("admin_example"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-title-5"))); + String reviewTitle = driver.findElement(By.id("review-title-5")).getText(); + assertThat(reviewTitle).isEqualTo("sample_title"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("review-valoration-5"))); + String reviewRating = driver.findElement(By.id("review-valoration-5")).getText(); + assertThat(reviewRating).isEqualTo("Valoración del producto: ★★★★★ 5/5"); + + } + + @Test + public void createVoidReviewTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/1"); + + scrollToAndClick(By.name("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 createInvalidReviewTest() { + + login("admin@example.com", "adminpass"); + + driver.get("http://localhost:5173/components/1"); + + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("title"))); + driver.findElement(By.id("title")).sendKeys("sample_title"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("message"))); + driver.findElement(By.id("message")).sendKeys("sample_message"); + wait.until(ExpectedConditions.presenceOfElementLocated(By.id("rating"))); + driver.findElement(By.id("rating")).sendKeys("-5"); + + scrollToAndClick(By.name("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 deleteReviewTest() { 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 ea8d2a6..d984f9f 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 @@ -373,6 +373,38 @@ void validateBadNumReviewData() { } + @Test + public void testHasUserReviewed() { + Component component = componentsRepository.findAll().getFirst(); + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + boolean res = reviewsService.hasUserReviewed(component.getId(), admin.getId()); + + assertEquals(true, res); + + } + + @Test + public void testHasNotUserReviewed() { + Component component = componentsRepository.findAll().getLast(); + 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_REGISTERED_USER", "ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); + + boolean res = reviewsService.hasUserReviewed(component.getId(), admin.getId()); + + assertEquals(false, res); + + } + @Test void deleteReviewAsNotLoggedIn() { 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 43f488a..852db25 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 @@ -172,9 +172,13 @@ public void testSaveReview() { when(reviewsRepository.existsByComponentIdAndUserId(1L, 1L)).thenReturn(false); when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); + when(reviewsRepository.save(any(Review.class))).thenReturn(review); - reviewsService.save(review, 1L, 1L); + Review savedReview = reviewsService.save(review, 1L, 1L); + assertEquals(review.getTitle(), savedReview.getTitle()); + assertEquals(review.getMessage(), savedReview.getMessage()); + assertEquals(review.getRating(), savedReview.getRating()); verify(reviewsRepository).save(any(Review.class)); } @@ -339,6 +343,36 @@ public void testBadNumReviewValidation() { } + @Test + public void testHasUserReviewed() { + + ReviewsRepository reviewsRepository = mock(ReviewsRepository.class); + ReviewsService reviewsService = new ReviewsService(reviewsRepository, null, null, null ); + + when(reviewsRepository.existsByComponentIdAndUserId(any(), any())).thenReturn(true); + + boolean res = reviewsService.hasUserReviewed(1L, 1L); + + assertEquals(true, res); + verify(reviewsRepository).existsByComponentIdAndUserId(1L, 1L); + + } + + @Test + public void testHasNotUserReviewed() { + + ReviewsRepository reviewsRepository = mock(ReviewsRepository.class); + ReviewsService reviewsService = new ReviewsService(reviewsRepository, null, null, null ); + + when(reviewsRepository.existsByComponentIdAndUserId(any(), any())).thenReturn(false); + + boolean res = reviewsService.hasUserReviewed(1L, 1L); + + assertEquals(false, res); + verify(reviewsRepository).existsByComponentIdAndUserId(1L, 1L); + + } + @Test public void testDeleteReview() { diff --git a/frontend/app/app.css b/frontend/app/app.css index 0dd3ce0..b6882ae 100644 --- a/frontend/app/app.css +++ b/frontend/app/app.css @@ -701,6 +701,63 @@ body { font-size: 1.3rem; } +.reviews-list .custom-review-form { + width: 100%; + margin-bottom: 1.25rem; + padding: 1.25rem; + background-color: #fffaf6; + border: 1px solid var(--color-line); + border-radius: 8px; + box-shadow: 0 4px 12px rgb(84 37 20 / 6%); + text-align: left; +} + +.reviews-list .custom-review-form .form { + gap: 1rem; + margin-bottom: 1.25rem; +} + +.reviews-list .custom-review-form .form h3 { + color: var(--color-ink); + font-size: 1.2rem; + font-weight: 700; +} + +.reviews-list .custom-review-form .form-field { + gap: 0.35rem; +} + +.reviews-list .custom-review-form .form-label { + margin-bottom: 0; + color: var(--color-brand-dark); + font-weight: 700; +} + +.reviews-list .custom-review-form .form-control { + min-height: 44px; + padding: 0.65rem 0.75rem; + background-color: var(--color-surface); + border-color: var(--color-line); +} + +.reviews-list .custom-review-form textarea.form-control { + min-height: 112px; + resize: vertical; +} + +.reviews-list .custom-review-form .form-control:focus { + border-color: var(--color-principal); + box-shadow: 0 0 0 3px rgb(249 94 0 / 14%); +} + +.reviews-list .custom-review-form .rating-input { + max-width: 180px; +} + +.reviews-list .custom-review-form>.pcmod-button { + margin: 0; +} + .reviews-list h4 { margin: 0; color: var(--color-muted); @@ -1397,6 +1454,14 @@ body { grid-template-columns: 1fr; } + .reviews-list .custom-review-form { + padding: 1rem; + } + + .reviews-list .custom-review-form .rating-input { + max-width: none; + } + .custom-component-form .pcmod-danger-button, .custom-component-form>.pcmod-button { width: 100%; diff --git a/frontend/app/components/reviewForm.tsx b/frontend/app/components/reviewForm.tsx new file mode 100644 index 0000000..ed43ab1 --- /dev/null +++ b/frontend/app/components/reviewForm.tsx @@ -0,0 +1,63 @@ +import type { SubmitEvent, RefObject } from "react"; +import { FormControl, FormLabel, Button } from "react-bootstrap"; +import { Star } from "react-bootstrap-icons"; + +interface ReviewFormProps { + onSubmit: (event: SubmitEvent) => void; + isPending: boolean; + wasValidated: boolean; + formRef: RefObject; + submitLabel?: string; +} + +export default function ComponentForm({ + onSubmit, + isPending, + wasValidated, + formRef, + submitLabel, +}: Readonly) { + + return ( +
+
+

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

+
+ Título: + +
+ Por favor, ingrese un título válido. +
+
+ +
+ Mensaje: + +
+ Por favor, ingrese un mensaje válido. +
+
+ +
+ Valoración: +
+ +
+ Por favor, ingrese una valoración válida. +
+
+
+
+ + +
+ ); +} \ No newline at end of file diff --git a/frontend/app/routes/detail-component.tsx b/frontend/app/routes/detail-component.tsx index c5ddff5..42d1120 100644 --- a/frontend/app/routes/detail-component.tsx +++ b/frontend/app/routes/detail-component.tsx @@ -1,20 +1,24 @@ import { Button, Col, Image, Modal } from "react-bootstrap"; -import { ArrowLeft, CartPlus, Image as ImageIcon, PencilSquare, Plus, Trash, XOctagon } from "react-bootstrap-icons"; +import { ArrowLeft, CartPlus, ExclamationCircleFill, Image as ImageIcon, PencilSquare, Plus, Trash, XOctagon } from "react-bootstrap-icons"; import type { Route } from "./+types/detail-component"; import { deleteComponent, getComponent } from "~/services/components-service"; import { useUserStore } from "~/stores/user-store"; -import { useEffect, useState } from "react"; +import { useActionState, useEffect, useRef, useState, type SubmitEvent } from "react"; import { Link, useNavigate, useRevalidator } from "react-router"; import ReviewCard from "~/components/reviewCard"; import type ReviewDTO from "~/dtos/ReviewDTO"; -import { getReviews } from "~/services/reviews-service"; +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"; const API_URL = "/api/v1/components"; export async function clientLoader({ params }: Route.ClientLoaderArgs) { const component = await getComponent(Number(params.id)); const reviews = await getReviews(component.id, 0); - return { component, reviews }; + const hasReviewed = await hasUserReviewed(component.id); + return { component, reviews, hasReviewed }; } function convertRatingToStars(rating: number) { @@ -38,6 +42,13 @@ 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); @@ -79,6 +90,30 @@ export default function ComponentDetail({ loaderData }: Route.ComponentProps) { } }; + async function createReviewAction(_prevState: ReviewFormValues, formData: FormData) { + const { title, message, rating } = getReviewFormValues(formData); + setErrorMessage(""); + + try { + await createReview(component.id, title, message, 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); + } + async function handleDeleteReview() { await revalidator.revalidate(); } @@ -137,6 +172,27 @@ export default function ComponentDetail({ loaderData }: Route.ComponentProps) {

Reseñas del producto:

Puntuación media: {convertRatingToStars(component.averageRating)} {component.averageRating}/5 ({component.reviews.length} reseña(s))

+ {user && !loaderData.hasReviewed && ( + <> + {errorMessage && ( +
+ + Error: + +

+ {errorMessage} +

+
+ )} + + + )} {reviews.length > 0 ? ( <> {reviews.map((review) => ( diff --git a/frontend/app/services/reviews-service.ts b/frontend/app/services/reviews-service.ts index 2e5f6a4..fabecb5 100644 --- a/frontend/app/services/reviews-service.ts +++ b/frontend/app/services/reviews-service.ts @@ -36,6 +36,56 @@ export async function getReviews(id: number, page: number): Promise { + + const url = new URL(`${API_URL}/${id}/reviews/`, getBaseUrl()); + const res = await fetch(url.toString(), { + method: "POST", + 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 creating the review."); + } + + return await res.json(); +} + +export async function hasUserReviewed(id: number): Promise { + + const url = new URL(`${API_URL}/${id}/reviews/has-reviewed`, getBaseUrl()); + const res = await fetch(url.toString()); + + 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 checking user review availability."); + } + + return await res.json(); +} + export async function deleteReview(id: number, reviewId: number): Promise { const url = new URL(`${API_URL}/${id}/reviews/${reviewId}`, getBaseUrl()); diff --git a/frontend/app/utils/review-form-utils.ts b/frontend/app/utils/review-form-utils.ts new file mode 100644 index 0000000..85d74c8 --- /dev/null +++ b/frontend/app/utils/review-form-utils.ts @@ -0,0 +1,15 @@ +export interface ReviewFormValues { + title: string; + message: string; + rating: number; +} + +export function getReviewFormValues(formData: FormData): ReviewFormValues { + + return { + title: (formData.get("title") as string) ?? "", + message: (formData.get("message") as string) ?? "", + rating: Number((formData.get("rating") as string) ?? 0), + }; + +} diff --git a/frontend/tests/integration/ComponentDetailPage.integration.test.tsx b/frontend/tests/integration/ComponentDetailPage.integration.test.tsx index ee4a12d..b77c7fa 100644 --- a/frontend/tests/integration/ComponentDetailPage.integration.test.tsx +++ b/frontend/tests/integration/ComponentDetailPage.integration.test.tsx @@ -385,6 +385,154 @@ describe("ComponentDetailPageIntegration", () => { }); + it("does not render the review form when user is not logged in", async () => { + + const RouterStub = createRoutesStub([, + { path: "/components/:id", Component: ComponentDetail, loader: clientLoader } + ]); + + render(); + + await waitFor(() => { + expect(screen.queryByText("¡Añade una reseña a este producto!")).not.toBeInTheDocument(); + }); + + }); + + it("does not render the review form when user has already reviewed the component", 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(screen.queryByText("¡Añade una reseña a este producto!")).not.toBeInTheDocument(); + }); + + }); + + it("renders the review form when user has not reviewed the component", 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(screen.queryByText("¡Añade una reseña a este producto!")).toBeInTheDocument(); + expect(screen.getByLabelText("Título:")).toBeInTheDocument(); + expect(screen.getByLabelText("Mensaje:")).toBeInTheDocument(); + expect(screen.getByLabelText("Valoración:")).toBeInTheDocument(); + }); + + }); + + it("creates a new review with valid 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:"), "admin@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "adminpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await screen.findByText("MAG A650BN"); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.type(screen.getByLabelText("Valoración:"), "5"); + + const createButton = await screen.findByRole("button", { name: /Guardar reseña/i }); + await user.click(createButton); + + await waitFor(() => { + expect(screen.getByText(/5\/5 \(1 reseña\(s\)\)/i)).toBeInTheDocument(); + expect(screen.getByText("sample_title")).toBeInTheDocument(); + expect(screen.getByText("sample_message")).toBeInTheDocument(); + expect(screen.getByText("Valoración del producto: ★★★★★ 5/5")).toBeInTheDocument(); + }); + + }); + + it("show error when creating a new 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 screen.findByText("MAG A650BN"); + + const createButton = await screen.findByRole("button", { name: /Guardar reseña/i }); + await user.click(createButton); + + await waitFor(() => { + 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 creating a new review with invalid 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 screen.findByText("MAG A650BN"); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.type(screen.getByLabelText("Valoración:"), "-5"); + + const createButton = await screen.findByRole("button", { name: /Guardar reseña/i }); + await user.click(createButton); + + await waitFor(() => { + expect(screen.getByText("Por favor, ingrese una valoración válida.")).toBeInTheDocument(); + }); + + }); + it("cancel review deletion", async () => { const user = userEvent.setup(); diff --git a/frontend/tests/unit/ComponentDetailPage.test.tsx b/frontend/tests/unit/ComponentDetailPage.test.tsx index 6dc27b4..be195c9 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 { deleteReview, getReviews } from "~/services/reviews-service"; +import { createReview, deleteReview, getReviews, hasUserReviewed } from "~/services/reviews-service"; import { reqIsLogged, getPublicUser } from "~/services/users-service"; import { useUserStore } from "~/stores/user-store"; import userEvent from "@testing-library/user-event"; @@ -17,7 +17,9 @@ vi.mock("~/services/components-service", () => ({ vi.mock("~/services/reviews-service", () => ({ getReviews: vi.fn(), - deleteReview: vi.fn() + createReview: vi.fn(), + deleteReview: vi.fn(), + hasUserReviewed: vi.fn(), })); const userPublic1 = { @@ -474,6 +476,7 @@ describe("ComponentDetailPage", () => { vi.mocked(getComponent).mockResolvedValue(component1); vi.mocked(getReviews).mockResolvedValue(reviews); + vi.mocked(hasUserReviewed).mockResolvedValue(false); const result = await clientLoader({ params: { id: "1" } } as Parameters[0]); @@ -481,7 +484,8 @@ describe("ComponentDetailPage", () => { expect(getComponent).toHaveBeenCalledWith(1); expect(getReviews).toHaveBeenCalledTimes(1); expect(getReviews).toHaveBeenCalledWith(component1.id, 0); - expect(result).toEqual({ component: component1, reviews }); + expect(hasUserReviewed).toHaveBeenCalledTimes(1); + expect(result).toEqual({ component: component1, reviews, hasReviewed: false}); }); @@ -494,14 +498,16 @@ describe("ComponentDetailPage", () => { vi.mocked(getComponent).mockResolvedValue(component2); vi.mocked(getReviews).mockResolvedValue(reviews); + vi.mocked(hasUserReviewed).mockResolvedValue(true); const result = await clientLoader({ params: { id: "2" } } as Parameters[0]); expect(getComponent).toHaveBeenCalledTimes(1); expect(getComponent).toHaveBeenCalledWith(2); expect(getReviews).toHaveBeenCalledTimes(1); + expect(hasUserReviewed).toHaveBeenCalledTimes(1); expect(getReviews).toHaveBeenCalledWith(component2.id, 0); - expect(result).toEqual({ component: component2, reviews }); + expect(result).toEqual({ component: component2, reviews, hasReviewed: true }); }); @@ -521,6 +527,192 @@ describe("ComponentDetailPage", () => { }); + it("does not render the review form when user is not logged in", async () => { + vi.mocked(getComponent).mockResolvedValue(component1); + + const RouterStub = createRoutesStub([ + { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component1, reviews: { items: [], hasNext: false } }) }, + ]); + + render(); + + await waitFor(() => { + expect(screen.queryByText("¡Añade una reseña a este producto!")).not.toBeInTheDocument(); + }); + + }); + + it("does not render the review form when user has already reviewed the component", async () => { + + const RouterStub = createRoutesStub([ + { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component2, reviews: { items: [review1, review2], hasNext: false } }) }, + ]); + + vi.mocked(reqIsLogged).mockResolvedValue(userAccount); + useUserStore.setState({ user: userAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(true); + + render(); + + await waitFor(() => { + expect(screen.queryByText("¡Añade una reseña a este producto!")).not.toBeInTheDocument(); + }); + + }); + + it("renders the review form when user has not reviewed the component", async () => { + + const RouterStub = createRoutesStub([ + { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component1, reviews: { items: [], hasNext: false } }) }, + ]); + + vi.mocked(reqIsLogged).mockResolvedValue(userAccount); + useUserStore.setState({ user: userAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(false); + + render(); + + await waitFor(() => { + expect(screen.queryByText("¡Añade una reseña a este producto!")).toBeInTheDocument(); + expect(screen.getByLabelText("Título:")).toBeInTheDocument(); + expect(screen.getByLabelText("Mensaje:")).toBeInTheDocument(); + expect(screen.getByLabelText("Valoración:")).toBeInTheDocument(); + }); + + }); + + it("creates a new review with valid data", async () => { + + const user = userEvent.setup(); + + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(false); + vi.mocked(createReview).mockImplementation(async () => { + reviewCreated = true; + + return { + id: 3, + title: "sample_title", + message: "sample_message", + rating: 5, + date: "2026-11-07", + componentId: 1, + user: adminPublic1 + }; + }); + + let reviewCreated = false; + + const RouterStub = createRoutesStub([ + { + path: "/components/:id", + Component: ComponentDetail, + loader: () => ({ + component: reviewCreated + ? { + ...component1, + averageRating: 5, + reviews: [{ id: 3 }] + } + : component1, + reviews: { + items: reviewCreated + ? [{ + id: 3, + title: "sample_title", + message: "sample_message", + rating: 5, + date: "2026-11-07", + componentId: 1, + user: adminPublic1 + }] + : [], + hasNext: false + }, + hasReviewed: reviewCreated + }) + } + ]); + + render(); + + await screen.findByText("AMD Ryzen 7 7800X3D"); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.type(screen.getByLabelText("Valoración:"), "5"); + + const createButton = await screen.findByRole("button", { name: /Guardar reseña/i }); + await user.click(createButton); + + await waitFor(() => { + expect(createReview).toHaveBeenCalledTimes(1); + expect(screen.getByText(/5\/5 \(1 reseña\(s\)\)/i)).toBeInTheDocument(); + expect(screen.getByText("sample_title")).toBeInTheDocument(); + expect(screen.getByText("sample_message")).toBeInTheDocument(); + expect(screen.getByText("Valoración del producto: ★★★★★ 5/5")).toBeInTheDocument(); + }); + + }); + + it("show error when creating a new review with void data", async () => { + + const user = userEvent.setup(); + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(false); + + const RouterStub = createRoutesStub([ + { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component1, reviews: { items: [], hasNext: false }, hasReviewed: false }) }, + ]); + + render(); + + const createButton = await screen.findByRole("button", { name: /Guardar reseña/i }); + await user.click(createButton); + + await waitFor(() => { + expect(createReview).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 creating a new review with invalid data", async () => { + + const user = userEvent.setup(); + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + + vi.mocked(hasUserReviewed).mockResolvedValue(false); + + const RouterStub = createRoutesStub([ + { path: "/components/:id", Component: ComponentDetail, loader: () => ({ component: component1, reviews: { items: [], hasNext: false }, hasReviewed: false }) }, + ]); + + render(); + + await screen.findByText("AMD Ryzen 7 7800X3D"); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.type(screen.getByLabelText("Valoración:"), "-5"); + + const createButton = await screen.findByRole("button", { name: /Guardar reseña/i }); + await user.click(createButton); + + await waitFor(() => { + expect(createReview).not.toHaveBeenCalled(); + expect(screen.getByText("Por favor, ingrese una valoración válida.")).toBeInTheDocument(); + }); + + }); + it("it does not show the review delete button for non-registered users", async () => { const RouterStub = createRoutesStub([ From c15ca75d245a8bf0e4b5874a3a919a1b7f6374d4 Mon Sep 17 00:00:00 2001 From: jaimeeg5 Date: Thu, 12 Nov 2026 12:51:07 +0100 Subject: [PATCH 3/3] test: add frontend review tests to improve code coverage --- .../ComponentDetailPage.integration.test.tsx | 112 ++++++++++++++++++ .../tests/unit/ComponentDetailPage.test.tsx | 109 +++++++++++++++++ 2 files changed, 221 insertions(+) diff --git a/frontend/tests/integration/ComponentDetailPage.integration.test.tsx b/frontend/tests/integration/ComponentDetailPage.integration.test.tsx index b77c7fa..47b18a4 100644 --- a/frontend/tests/integration/ComponentDetailPage.integration.test.tsx +++ b/frontend/tests/integration/ComponentDetailPage.integration.test.tsx @@ -533,6 +533,118 @@ describe("ComponentDetailPageIntegration", () => { }); + it("shows the backend error with message when creating 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:"), "admin@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "adminpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await screen.findByText("AMD Ryzen 7 7800X3D"); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + 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: /Guardar reseña/i })); + + await waitFor(() => { + expect(screen.getByText(backendErrorMessage)).toBeInTheDocument(); + expect(screen.getByText("¡Añade una reseña a este producto!")).toBeInTheDocument(); + }); + }); + + it("shows the backend error without message when creating 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:"), "admin@example.com"); + await user.type(screen.getByLabelText("Contraseña:"), "adminpass"); + await user.click(screen.getByRole("button", { name: /Iniciar sesión/i })); + + await screen.findByText("AMD Ryzen 7 7800X3D"); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + 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: /Guardar reseña/i })); + + await waitFor(() => { + expect(screen.getByText("There was an error while creating the review.")).toBeInTheDocument(); + expect(screen.getByText("¡Añade una reseña a este producto!")).toBeInTheDocument(); + }); + }); + + it("shows the backend error with message when checking user review availability fails", async () => { + const backendErrorMessage = "sample_backend_error"; + const originalFetch = globalThis.fetch; + + vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => { + if (String(input).includes("/reviews/has-reviewed")) { + return Promise.resolve( + new Response( + JSON.stringify({ message: backendErrorMessage }), + { status: 400, headers: { "Content-Type": "application/json" } }, + ), + ); + } + + return originalFetch(input, init); + }); + + await expect( + clientLoader({ params: { id: "1" } } as Parameters[0]), + ).rejects.toThrow(backendErrorMessage); + }); + + it("shows the backend error without message when checking user review availability fails", async () => { + const originalFetch = globalThis.fetch; + + vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => { + if (String(input).includes("/reviews/has-reviewed")) { + return Promise.resolve( + new Response( + JSON.stringify({}), + { status: 400, headers: { "Content-Type": "application/json" } }, + ), + ); + } + + return originalFetch(input, init); + }); + + await expect( + clientLoader({ params: { id: "1" } } as Parameters[0]), + ).rejects.toThrow("There was an error while checking user review availability."); + }); + it("cancel review deletion", async () => { const user = userEvent.setup(); diff --git a/frontend/tests/unit/ComponentDetailPage.test.tsx b/frontend/tests/unit/ComponentDetailPage.test.tsx index be195c9..4289188 100644 --- a/frontend/tests/unit/ComponentDetailPage.test.tsx +++ b/frontend/tests/unit/ComponentDetailPage.test.tsx @@ -120,6 +120,7 @@ describe("ComponentDetailPage", () => { beforeEach(() => { vi.clearAllMocks(); + vi.unstubAllGlobals(); useUserStore.setState({ user: null }); vi.mocked(reqIsLogged).mockResolvedValue(null as never); }); @@ -511,6 +512,41 @@ describe("ComponentDetailPage", () => { }); + it("clientLoader throws the backend error when checking user review availability fails", async () => { + const backendErrorMessage = "sample_backend_error"; + const reviews = { + items: [], + hasNext: false, + }; + + vi.mocked(getComponent).mockResolvedValue(component1); + vi.mocked(getReviews).mockResolvedValue(reviews); + vi.mocked(hasUserReviewed).mockRejectedValue(new Error(backendErrorMessage)); + + await expect( + clientLoader({ params: { id: "1" } } as Parameters[0]), + ).rejects.toThrow(backendErrorMessage); + + }); + + it("clientLoader throws the default error when checking user review availability fails without a message", async () => { + const reviews = { + items: [], + hasNext: false, + }; + + vi.mocked(getComponent).mockResolvedValue(component1); + vi.mocked(getReviews).mockResolvedValue(reviews); + vi.mocked(hasUserReviewed).mockRejectedValue( + new Error("There was an error while checking user review availability."), + ); + + await expect( + clientLoader({ params: { id: "1" } } as Parameters[0]), + ).rejects.toThrow("There was an error while checking user review availability."); + + }); + it("gets public user info", async () => { const originalPublicUser = { @@ -713,6 +749,79 @@ describe("ComponentDetailPage", () => { }); + it("throws an error when the createReview 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(false); + vi.mocked(createReview).mockRejectedValue(new Error(backendErrorMessage)); + + const RouterStub = createRoutesStub([ + { + path: "/components/:id", + Component: ComponentDetail, + loader: () => ({ + component: component1, + reviews: { items: [], hasNext: false }, + hasReviewed: false, + }), + }, + ]); + + render(); + + await screen.findByText("AMD Ryzen 7 7800X3D"); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.type(screen.getByLabelText("Valoración:"), "5"); + await user.click(screen.getByRole("button", { name: /Guardar reseña/i })); + + await waitFor(() => { + expect(createReview).toHaveBeenCalledWith(1, "sample_title", "sample_message", 5); + expect(screen.getByText(backendErrorMessage)).toBeInTheDocument(); + expect(screen.getByText("¡Añade una reseña a este producto!")).toBeInTheDocument(); + }); + + }); + + it("throws the default error when the createReview request fails with a backend message", async () => { + const user = userEvent.setup(); + + vi.mocked(reqIsLogged).mockResolvedValue(adminAccount); + useUserStore.setState({ user: adminAccount }); + vi.mocked(hasUserReviewed).mockResolvedValue(false); + vi.mocked(createReview).mockRejectedValue(new Error("There was an error while creating the review.")); + + const RouterStub = createRoutesStub([ + { + path: "/components/:id", + Component: ComponentDetail, + loader: () => ({ + component: component1, + reviews: { items: [], hasNext: false }, + hasReviewed: false, + }), + }, + ]); + + render(); + + await screen.findByText("AMD Ryzen 7 7800X3D"); + await user.type(screen.getByLabelText("Título:"), "sample_title"); + await user.type(screen.getByLabelText("Mensaje:"), "sample_message"); + await user.type(screen.getByLabelText("Valoración:"), "5"); + await user.click(screen.getByRole("button", { name: /Guardar reseña/i })); + + await waitFor(() => { + expect(createReview).toHaveBeenCalledWith(1, "sample_title", "sample_message", 5); + expect(screen.getByText("There was an error while creating the review.")).toBeInTheDocument(); + expect(screen.getByText("¡Añade una reseña a este producto!")).toBeInTheDocument(); + }); + + }); + it("it does not show the review delete button for non-registered users", async () => { const RouterStub = createRoutesStub([