Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 100 additions & 5 deletions __tests__/groups/group.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function resetUserPermission() {
describe('Discord Groups Page', () => {
let browser;
let page;
jest.setTimeout(60000);
jest.setTimeout(120000);

beforeAll(async () => {
browser = await puppeteer.launch({
Expand Down Expand Up @@ -62,7 +62,14 @@ describe('Discord Groups Page', () => {
},
body: JSON.stringify(allUsersData.users[0]),
});

} else if (url.startsWith(`${BASE_URL}/discord-actions/groups`)) {
const urlParams = new URLSearchParams(url.split('?')[1]);
const latestDoc = urlParams.get('latestDoc');
const paginatedGroups = getPaginatedGroups(latestDoc);

} else if (url === `${STAGING_API_URL}/discord-actions/groups`) {

interceptedRequest.respond({
status: 200,
contentType: 'application/json',
Expand All @@ -71,6 +78,9 @@ describe('Discord Groups Page', () => {
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},

body: JSON.stringify(paginatedGroups),

body: JSON.stringify(discordGroups),
});
} else if (url === `${STAGING_API_URL}/discord-actions/groups`) {
Expand All @@ -83,6 +93,7 @@ describe('Discord Groups Page', () => {
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
body: JSON.stringify(discordGroups),

});
} else if (url === `${STAGING_API_URL}/discord-actions/roles`) {
interceptedRequest.respond({
Expand All @@ -102,7 +113,6 @@ describe('Discord Groups Page', () => {
if (url === `${STAGING_API_URL}/discord-actions/groups`) {
const postData = interceptedRequest.postData();
const groupData = JSON.parse(postData);
// discordGroups.push(groupData);
interceptedRequest.respond({
status: 201,
contentType: 'application/json',
Expand Down Expand Up @@ -146,8 +156,13 @@ describe('Discord Groups Page', () => {
interceptedRequest.continue();
}
});

await page.goto(`${PAGE_URL}/groups`);
await page.waitForSelector('.card', { timeout: 5000 }); // Wait for the first batch of cards to load

await page.goto(`${LOCAL_TEST_PAGE_URL}/groups`);
await page.waitForNetworkIdle();

});

afterAll(async () => {
Expand All @@ -160,7 +175,6 @@ describe('Discord Groups Page', () => {
});

test('Should display cards', async () => {
await page.waitForSelector('.card');
const cards = await page.$$('.card');

expect(cards.length).toBeGreaterThan(0);
Expand Down Expand Up @@ -252,12 +266,71 @@ describe('Discord Groups Page', () => {
const closeBtn = await groupCreationModal.$('#close-button');

await closeBtn.click();
await page.waitForTimeout(500); // Wait for modal to close
const groupCreationModalClosed = await page.$('.group-creation-modal');

expect(groupCreationModalClosed).toBeFalsy();
});


test('Should load more groups on scroll', async () => {
await page.goto(`${PAGE_URL}/groups`);
await page.waitForSelector('.card', { timeout: 10000 });

const initialGroupCount = await page.$$eval(
'.card',
(cards) => cards.length,
);

await page.evaluate(() => {
window.scrollTo(0, document.body.scrollHeight);
});

await page.waitForFunction(
(initialCount) => {
return document.querySelectorAll('.card').length > initialCount;
},
{ timeout: 60000 },
initialGroupCount,
);

const newGroupCount = await page.$$eval('.card', (cards) => cards.length);

expect(newGroupCount).toBeGreaterThan(initialGroupCount);
}, 120000);

test('Should stop loading more groups when all groups are loaded', async () => {
await page.goto(`${PAGE_URL}/groups`);
await page.waitForSelector('.card', { timeout: 5000 });

// Scroll to the bottom multiple times
for (let i = 0; i < 5; i++) {
await page.evaluate(() => {
window.scrollTo(0, document.body.scrollHeight);
});
await page.waitForTimeout(1000);
}

const finalGroupCount = await page.$$eval('.card', (cards) => cards.length);

// Scroll one more time
await page.evaluate(() => {
window.scrollTo(0, document.body.scrollHeight);
});
await page.waitForTimeout(1000);

const newFinalGroupCount = await page.$$eval(
'.card',
(cards) => cards.length,
);

expect(newFinalGroupCount).toBe(finalGroupCount);
});

test('Should display only specified groups when dev=true and name=<group-name> with different case', async () => {

test('Should display only specified groups when name=<group-name> with different case', async () => {

const groupNames = 'fIrSt,DSA+COdInG';
await page.goto(`${LOCAL_TEST_PAGE_URL}/groups?name=${groupNames}`);
await page.waitForNetworkIdle();
Expand All @@ -268,15 +341,20 @@ describe('Discord Groups Page', () => {
);
});

expect(displayedGroups).toEqual(['First Daaa', 'DSA Coding Group']);
expect(displayedGroups).toContain('First Daaa');
expect(displayedGroups).toContain('DSA Coding Group');
});

test('Should display no group found div when no group is present', async () => {

await page.goto(`${PAGE_URL}/groups?dev=true&name=no-group-present`);
await page.waitForSelector('.no-group-container', { timeout: 5000 });

await page.goto(`${LOCAL_TEST_PAGE_URL}/groups?name=no-group-present`);
await page.waitForNetworkIdle();

const noGroupDiv = await page.$('.no-group-container');

const noGroupDiv = await page.$('.no-group-container');
expect(noGroupDiv).toBeTruthy();
});

Expand Down Expand Up @@ -385,3 +463,20 @@ describe('Discord Groups Page', () => {
expect(loaderAfter).toBeFalsy();
});
});

// Helper function to simulate paginated data
function getPaginatedGroups(latestDoc) {
const pageSize = 18;
const startIndex = latestDoc
? discordGroups.groups.findIndex((g) => g.id === latestDoc) + 1
: 0;
const endIndex = startIndex + pageSize;
const groups = discordGroups.groups.slice(startIndex, endIndex);
const newLatestDoc = groups.length > 0 ? groups[groups.length - 1].id : null;

return {
message: 'Roles fetched successfully!',
groups,
newLatestDoc,
};
}
13 changes: 13 additions & 0 deletions groups/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,25 @@
</section>
<div class="group-container"></div>
</main>

<footer>
<p class="info-repo">
The contents of this website are deployed from this
<a
href="https://github.com/Real-Dev-Squad/website-dashboard"
target="_blank"
rel="noopener noreferrer"
>open sourced repo</a
>
</p>
</footer>
<script>
document.addEventListener('DOMContentLoaded', () => {
loadFooter();
});
</script>
<script src="../footer/footerComponent.js"></script>

</body>
<div class="toast">
<div class="toast__message"></div>
Expand Down
131 changes: 131 additions & 0 deletions groups/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
addGroupRoleToMember,
createDiscordGroupRole,
getDiscordGroups,
getPaginatedDiscordGroups,
getUserGroupRoles,
getUserSelf,
removeRoleFromMember,
Expand Down Expand Up @@ -109,6 +110,8 @@ const handler = {
obj[prop] = value;
break;
case 'discordId':
case 'isLoading':
case 'hasMoreGroups':
obj[prop] = value;
break;
case 'isSuperUser':
Expand All @@ -125,11 +128,19 @@ const dataStore = new Proxy(
{
userSelf: null,
groups: null,

filteredGroupsIds: isDev ? [] : null,
search: isDev ? getParamValueFromURL(QUERY_PARAM_KEY.GROUP_SEARCH) : '',
discordId: null,
isGroupCreationModalOpen: false,
isLoading: false,
hasMoreGroups: true,
filteredGroupsIds: null,
search: getParamValueFromURL(QUERY_PARAM_KEY.GROUP_SEARCH),
discordId: null,
isCreateGroupModalOpen: false,
isSuperUser: false,

},
handler,
);
Expand All @@ -150,6 +161,7 @@ const onCreate = () => {
throw new Error(data);
}
dataStore.userSelf = data;
isDev ? removeLoadingCards() : null;
removeLoadingNavbarProfile();
await afterAuthentication();
})
Expand All @@ -168,9 +180,116 @@ const onCreate = () => {
bindSearchInput();
bindSearchFocus();
bindGroupCreationButton();
isDev ? bindInfiniteScroll() : null;
};
const afterAuthentication = async () => {
renderNavbarProfile({ profile: dataStore.userSelf });

if (isDev) {
await Promise.all([loadMoreGroups(), getUserGroupRoles()]).then(
([groups, roleData]) => {
dataStore.filteredGroupsIds = groups.map((group) => group.id);
dataStore.groups = groups.reduce((acc, group) => {
let title = group.rolename
.replace('group-', '')
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
acc[group.id] = {
id: group.id,
title: title,
count: group.memberCount,
isMember: group.isMember,
roleId: group.roleid,
description: group.description,
isUpdating: false,
};
return acc;
}, {});
if (isDev) {
dataStore.filteredGroupsIds = getDiscordGroupIdsFromSearch(
Object.values(dataStore.groups),
dataStore.search,
);
}
dataStore.discordId = roleData.userId;
},
);
} else {
await Promise.all([getDiscordGroups(), getUserGroupRoles()]).then(
([groups, roleData]) => {
dataStore.filteredGroupsIds = groups.map((group) => group.id);
dataStore.groups = groups.reduce((acc, group) => {
let title = group.rolename
.replace('group-', '')
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
acc[group.id] = {
id: group.id,
title: title,
count: group.memberCount,
isMember: group.isMember,
roleId: group.roleid,
description: group.description,
isUpdating: false,
};
return acc;
}, {});
if (isDev) {
dataStore.filteredGroupsIds = getDiscordGroupIdsFromSearch(
Object.values(dataStore.groups),
dataStore.search,
);
}
dataStore.discordId = roleData.userId;
},
);
}
};
const loadMoreGroups = async () => {
if (dataStore.isLoading || !dataStore.hasMoreGroups) return;

dataStore.isLoading = true;
renderLoadingCards();

const newGroups = await getPaginatedDiscordGroups();

removeLoadingCards();
dataStore.isLoading = false;

if (newGroups.length === 0) {
dataStore.hasMoreGroups = false;
return;
}

dataStore.groups = {
...dataStore.groups,
...newGroups.reduce((acc, group) => {
acc[group.id] = {
id: group.id,
title: group.rolename
.replace('group-', '')
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' '),
count: group.memberCount,
isMember: group.isMember,
roleId: group.roleid,
description: group.description,
isUpdating: false,
};
return acc;
}, {}),
};

dataStore.filteredGroupsIds = [
...dataStore.filteredGroupsIds,
...newGroups.map((group) => group.id),
];

return newGroups;

dataStore.isSuperUser = await checkUserIsSuperUser();

await Promise.all([getDiscordGroups(), getUserGroupRoles()]).then(
Expand Down Expand Up @@ -204,10 +323,22 @@ const afterAuthentication = async () => {
});
},
);

};

// Bind Functions

const bindInfiniteScroll = () => {
window.addEventListener('scroll', () => {
if (
window.innerHeight + window.scrollY >=
document.body.offsetHeight - 100
) {
loadMoreGroups();
}
});
};

const bindGroupCreationButton = () => {
const groupCreationBtn = document.querySelector('.create-group');

Expand Down
Loading