Skip to content

Commit

Permalink
Merge branch 'develop-test' of https://github.com/Arquisoft/wiq_es05b
Browse files Browse the repository at this point in the history
…into develop-test
  • Loading branch information
uo289321 committed Apr 10, 2024
2 parents e6e9c98 + 305737c commit b6bc6ee
Show file tree
Hide file tree
Showing 4 changed files with 255 additions and 11 deletions.
2 changes: 0 additions & 2 deletions users/authservice/repositories/userRepository.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const { checkUp } = require("../../../userhistory/repositories/saveRepository");

module.exports = {
mongoose: null,
uri: null,
Expand Down
13 changes: 5 additions & 8 deletions users/userservice/repositories/userRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ module.exports = {
this.uri = uri;
},
checkUp: async function () {
if (this.mongoose.connection.readyState != 1) {
if (this.mongoose.connection.readyState !== 1) {
await this.mongoose.connect(this.uri);
}
},
insertUser: async function (username, password) {
try {
this.checkUp()
await this.checkUp()
const user = new this.User({
username: username,
password: password,
Expand All @@ -25,13 +25,10 @@ module.exports = {
}
},
getUser: async function (filter) {
if ("_id" in filter) {
filter._id = new this.mongoose.Types.ObjectId(filter._id);
}
if ("_id" in filter) filter._id = new this.mongoose.Types.ObjectId(filter._id);
try {
this.checkUp()
let result = await this.mongoose.connection.collection("users").findOne(filter)
return result;
await this.checkUp()
return await this.mongoose.connection.collection("users").findOne(filter)
} catch (error) {
throw error.message;
}
Expand Down
2 changes: 1 addition & 1 deletion users/userservice/user-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ app.use(bodyParser.json());
const dataMiddleware = require('./middleware/DataMiddleware')
app.use("/adduser", dataMiddleware)

userRepository.init(mongoose);
userRepository.init(mongoose, mongoUri);
require('./routes/routes')(app, userRepository)

const server = app.listen(port, () => {
Expand Down
249 changes: 249 additions & 0 deletions webapp/src/__test__/Signup.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
import React from 'react';
import { render, fireEvent, screen, waitFor, act } from '@testing-library/react';
import axios from 'axios';
import Signup from '../views/Signup.jsx';
import { AuthContext } from "../views/context/AuthContext.jsx";
import {MemoryRouter} from "react-router";
import { useAuth } from "../App.jsx";
import '@testing-library/jest-dom';

jest.mock('axios');
jest.mock('../views/context/AuthContext');

const localStorageMock = (() => {
let store = {};
return {
getItem: key => store[key],
setItem: (key, value) => { store[key] = value },
removeItem: key => { delete store[key] },
clear: () => { store = {} }
};
})();

Object.defineProperty(window, 'localStorage', { value: localStorageMock });

// Configura una implementación simulada de axios
jest.mock('../App.jsx', () => ({
useAuth: jest.fn().mockReturnValue({
getUser: jest.fn(),
isAuthenticated: jest.fn().mockReturnValue(true),
logout: jest.fn(),
setUser: jest.fn()
})
}));

describe('Signup component', () => {

const mockAuth = useAuth();

beforeEach(() => {
axios.post.mockReset();
});

it('should sign up successfully', async () => {

await act(() => render(
<AuthContext.Provider value={mockAuth}>
<MemoryRouter><Signup /></MemoryRouter>
</AuthContext.Provider>
));

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const signUpButton = screen.getByRole('button');

// Mock the axios.post request to simulate a successful response
axios.post.mockResolvedValue({ data: { createdAt: '2024-01-01T12:34:56Z' } });

// Simulate user input
await act(async () => {
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
fireEvent.click(signUpButton);
});

waitFor(() => {
expect(history.location.pathname).toBe("/home");
})
});

it('should handle error when sign in (no special character)', async () => {
await act(() => render(
<AuthContext.Provider value={mockAuth}>
<MemoryRouter><Signup /></MemoryRouter>
</AuthContext.Provider>
));

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const signUpButton = screen.getByRole('button');

// Mock the axios.post request to simulate an error response
axios.post.mockRejectedValue({
response: {
status: 401,
data: { error: 'Password must contain at least one special character' }
}
});

// Simulate user input
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword123' } });

// Trigger the login button click
fireEvent.click(signUpButton);

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Password must contain at least one special character/i)).toBeInTheDocument();
});

waitFor(() => {
expect(history.location.pathname).toBe("/signup");
})
});

it('should handle error when sign in (no upper case)', async () => {
await act(() => render(
<AuthContext.Provider value={mockAuth}>
<MemoryRouter><Signup /></MemoryRouter>
</AuthContext.Provider>
));

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const signUpButton = screen.getByRole('button');

// Mock the axios.post request to simulate an error response
axios.post.mockRejectedValue({
response: {
status: 401,
data: { error: 'Password must contain at least one uppercase letter' }
}
});

// Simulate user input
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testpassword123$' } });

// Trigger the login button click
fireEvent.click(signUpButton);

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Password must contain at least one uppercase letter/i)).toBeInTheDocument();
});

waitFor(() => {
expect(history.location.pathname).toBe("/signup");
})
});

it('should handle error when sign in (no number)', async () => {
await act(() => render(
<AuthContext.Provider value={mockAuth}>
<MemoryRouter><Signup /></MemoryRouter>
</AuthContext.Provider>
));

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const signUpButton = screen.getByRole('button');

// Mock the axios.post request to simulate an error response
axios.post.mockRejectedValue({
response: {
status: 401,
data: { error: 'Password must contain at least one number' }
}
});

// Simulate user input
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword%' } });

// Trigger the login button click
fireEvent.click(signUpButton);

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Password must contain at least one number/i)).toBeInTheDocument();
});

waitFor(() => {
expect(history.location.pathname).toBe("/signup");
})
});

it('should handle error when sign in (length)', async () => {
await act(() => render(
<AuthContext.Provider value={mockAuth}>
<MemoryRouter><Signup /></MemoryRouter>
</AuthContext.Provider>
));

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const signUpButton = screen.getByRole('button');

// Mock the axios.post request to simulate an error response
axios.post.mockRejectedValue({
response: {
status: 401,
data: { error: 'Password must be at least 8 characters long' }
}
});

// Simulate user input
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'tes' } });

// Trigger the login button click
fireEvent.click(signUpButton);

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Password must be at least 8 characters long/i)).toBeInTheDocument();
});

waitFor(() => {
expect(history.location.pathname).toBe("/signup");
})
});

it('should handle error when sign in (repeated user)', async () => {
await act(() => render(
<AuthContext.Provider value={mockAuth}>
<MemoryRouter><Signup /></MemoryRouter>
</AuthContext.Provider>
));

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const signUpButton = screen.getByRole('button');

// Mock the axios.post request to simulate an error response
axios.post.mockRejectedValue({
response: {
status: 401,
data: { error: 'Username already exists' }
}
});

// Simulate user input
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword123$' } });

// Trigger the login button click
fireEvent.click(signUpButton);

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Username already exists/i)).toBeInTheDocument();
});

waitFor(() => {
expect(history.location.pathname).toBe("/signup");
})
});
});

0 comments on commit b6bc6ee

Please sign in to comment.