Skip to content

Commit

Permalink
Changes on tests
Browse files Browse the repository at this point in the history
  • Loading branch information
UO287687 committed Apr 7, 2024
1 parent c63b5c2 commit 103b43b
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 6 deletions.
4 changes: 0 additions & 4 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,6 @@ app.post('/addgame', async (req, res) => {
app.get('/getParticipation/:userId', async (req, res) => {
try {
const userId = req.params.userId;
if (!userId) {
res.status(404).json({ error: 'User ID not provided' });
return;
}
const apiUrl = `${gameServiceUrl}/getParticipation/${userId}`;
try{
const gameResponse = await axios.get(apiUrl);
Expand Down
43 changes: 41 additions & 2 deletions gatewayservice/gateway-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ describe('Gateway Service', () => {
}
});
}
else if (url.endsWith('/addgame')) {
return Promise.resolve({
data: {
user: userId,
pAcertadas: 5,
pFalladas: 3,
totalTime: 1200,
gameMode: 'normal'
}
});
}
});
axios.get.mockImplementation((url) => {
if (url.endsWith('/api/questions/create')) {
Expand Down Expand Up @@ -69,6 +80,23 @@ describe('Gateway Service', () => {
return Promise.resolve({ data: { username: 'testuser' } });
}
});


it('should return 401 Unauthorized if authorization token is missing', async () => {
const response = await request(app).post('/addgame');
expect(response.statusCode).toBe(401);
expect(response.body).toEqual({ error: 'Unauthorized' });
});

it('should return 401 Unauthorized if authorization token is invalid', async () => {
const mockedToken = 'invalidToken';
axios.get.mockRejectedValueOnce({ response: { status: 401 } });
const response = await request(app)
.post('/addgame')
.set('Authorization', `Bearer ${mockedToken}`);
expect(response.statusCode).toBe(401);
expect(response.body).toEqual({ error: 'Unauthorized' });
});
// Test /health endpoint
it('should give information of the status', async () => {
const response = await request(app)
Expand All @@ -89,13 +117,24 @@ describe('Gateway Service', () => {
});
// Test /verify endpoint
it('should verify authorization token with auth service', async () => {
const mockedToken = 'mockedToken';
const authResponse = { username: 'testuser' };
axios.get.mockResolvedValueOnce({ data: authResponse });
const response = await request(app)
.get('/verify')
.set('Authorization', 'Bearer mockedToken');
.set('Authorization', `Bearer ${mockedToken}`);
expect(response.statusCode).toBe(200);
expect(response.body).toHaveProperty('username', 'testuser');
expect(response.body).toEqual(authResponse);
});
it("should return 401 Unauthorized for unauthorized request", async () => {
const response = await request(app).get("/verify");
expect(response.statusCode).toBe(401);
expect(response.body).toEqual({ error: "Unauthorized" });
});




// Test /adduser endpoint
it('should forward add user request to user service', async () => {
const response = await request(app)
Expand Down
36 changes: 36 additions & 0 deletions webapp/src/test/AddUser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,40 @@ describe('AddUser component', () => {
fireEvent.click(button5);

});
it('should handle successful user registration and login', async () => {
render(
<SessionContext.Provider value={{ saveSessionData: () => {},clearSessionData: jest.fn() }}>
<AddUser goTo={(parameter) => {}}/>
</SessionContext.Provider>
);

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText('Password');
const confirmPasswordInput = screen.getByLabelText(/Confirm/i);
const addUserButton = screen.getByRole('button', { name: /SIGN UP/i });

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

// Mock the axios.post request to simulate a successful response
mockAxios.onPost('http://localhost:8000/adduser').reply(200);
mockAxios.onPost(`http://localhost:8000/login`).reply(200, {
createdAt: '2022-01-01',
username: 'testUser',
token: 'testToken',
profileImage: 'testProfileImage',
userId: 'testUserId',
});

// Trigger the add user button click
fireEvent.click(addUserButton);

// Wait for the Snackbar to be open
await waitFor(() => {
expect(screen.queryByText(/Passwords do not match/i)).toBeNull();
});
});

});
32 changes: 32 additions & 0 deletions webapp/src/test/PostGame.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,36 @@ describe('PostGame component', () => {
// Check if the snackbar is displayed
expect(await screen.findByText('Game saved successfully')).toBeInTheDocument();
});
test('closes the snackbar correctly', () => {
// Mock the SessionContext value
const sessionData = {
userId: 'mockedUserId',
token: 'mockedToken'
};

// Mock the setOpenSnackbar function
const setOpenSnackbar = jest.fn();
const handleCloseSnackbar = jest.fn();
render(
<SessionContext.Provider value={{ sessionData }}>
<PostGame setOpenSnackbar={setOpenSnackbar} handleCloseSnackbar={handleCloseSnackbar} />
</SessionContext.Provider>
);

// Set the initial state of the snackbar to open
act(() => {
setOpenSnackbar(false);
});

// Call the handleCloseSnackbar function
act(() => {
handleCloseSnackbar();
});

// Check if setOpenSnackbar is false
expect(setOpenSnackbar).toHaveBeenCalledWith(false);

// Check if the snackbar is closed
expect(screen.queryByText('Game saved successfully')).not.toBeInTheDocument();
});
});

0 comments on commit 103b43b

Please sign in to comment.