0% found this document useful (0 votes)
4 views13 pages

sql

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

sql

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

/**

* @jest-environment ./src/environments/test.environment.ts
*/

import { INestApplication } from '@nestjs/common';


import { getModelToken } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import { when } from 'jest-when';
import { Model } from 'mongoose';
import {
Activity,
ActivityDocument,
Community,
CommunityDocument,
Tournament,
TournamentDocument,
} from '../../../../schemas';
import { AppModule } from '../../../app.module';
import { FirebaseAdminService } from '../../../firebase-admin/firebase-
admin.service';
import { WebportalService } from '../../../webportal/webportal.service';
import { CommunityService } from '../../community.service';

jest.setTimeout(20000);

describe('Community Service (unit)', () => {


// describe('getActivityByGroupID', () => {
// let app: INestApplication,
// communityService: CommunityService,
// moduleFixture: TestingModule,
// tournamentModel: Model<TournamentDocument>,
// activityModel: Model<ActivityDocument>;

// beforeEach(async () => {
// moduleFixture = await Test.createTestingModule({
// imports: [AppModule],
// })
// .overrideProvider(FirebaseAdminService)
// .useValue({
// uploadFile: jest.fn(() => {
// return Promise.resolve(['https://subdomain.domain.com/name']);
// }),
// getFirebaseApp: jest.fn(() => {
// return {};
// }),
// })
// .compile();

// app = moduleFixture.createNestApplication({
// cors: true,
// bodyParser: false,
// logger: ['error'],
// });
// await app.init();
// communityService = await app.resolve<CommunityService>(CommunityService);

// tournamentModel = await app.get<Model<TournamentDocument>>(


// getModelToken(Tournament.name),
// );
// activityModel = await app.get<Model<ActivityDocument>>(
// getModelToken(Activity.name),
// );
// });

// afterEach(async () => {
// await tournamentModel.deleteMany({});
// await activityModel.deleteMany({});
// await app.close();
// });

// it('should return error when activity not found', async () => {


// const groupId = 'test id';
// const filter = 'upcoming';

// const webPortalServiceMock =
// moduleFixture.get<WebportalService>(WebportalService);
// when(jest.spyOn(webPortalServiceMock, 'getClubAllActivities'))
// .calledWith(groupId)
// .mockResolvedValue(true);

// const resp = await communityService.getActivityByGroupID(groupId, filter);


// expect(resp).toStrictEqual({
// error: 'Activity not found for this group',
// });
// });

// it('should return feed when activity and tournament exist', async () => {
// const groupId = 'test id';
// const filter = 'completed';

// const webPortalServiceMock =
// moduleFixture.get<WebportalService>(WebportalService);
// when(jest.spyOn(webPortalServiceMock, 'getClubAllActivities'))
// .calledWith(groupId)
// .mockResolvedValue(null);

// await tournamentModel.create(getTournamentMock(groupId));
// await activityModel.create(getActivityModelMock(groupId));

// const resp: any[] | { error: string } =


// await communityService.getActivityByGroupID(groupId, filter);

// expect((resp as { error: string }).error).toEqual(undefined);

// expect(Array.isArray(resp)).toBeTruthy();
// expect((resp as any[]).length).toEqual(2);
// expect((resp as any[]).map((el) => el.groupId)).toEqual([
// groupId,
// groupId,
// ]);
// expect(
// (resp as any[]).some((el) => el.email === '[email protected]'),
// ).toBeTruthy();
// expect(
// (resp as any[]).some((el) => el.email === '[email protected]'),
// ).toBeTruthy();
// });
// it('should return feed when only activity exist', async () => {
// const groupId = 'test id';
// const filter = 'completed';

// const webPortalServiceMock =
// moduleFixture.get<WebportalService>(WebportalService);
// when(jest.spyOn(webPortalServiceMock, 'getClubAllActivities'))
// .calledWith(groupId)
// .mockResolvedValue(null);

// await activityModel.create(getActivityModelMock(groupId));

// const resp: any[] | { error: string } =


// await communityService.getActivityByGroupID(groupId, filter);

// expect((resp as { error: string }).error).toEqual(undefined);

// expect(Array.isArray(resp)).toBeTruthy();
// expect((resp as any[]).length).toEqual(1);
// expect((resp as any[]).map((el) => el.groupId)).toEqual([groupId]);
// expect(
// (resp as any[]).some((el) => el.email === '[email protected]'),
// ).toBeTruthy();
// expect(
// (resp as any[]).some((el) => el.email === '[email protected]'),
// ).toBeFalsy();
// });

// it('should return error when data exist but not match in date filter', async
() => {
// const groupId = 'test 123123';
// const filter = 'upcoming';

// const webPortalServiceMock =
// moduleFixture.get<WebportalService>(WebportalService);
// when(jest.spyOn(webPortalServiceMock, 'getClubAllActivities'))
// .calledWith(groupId)
// .mockResolvedValue(null);

// await tournamentModel.create(getTournamentMock(groupId));
// await activityModel.create(getActivityModelMock(groupId));

// const resp: any[] | { error: string } =


// await communityService.getActivityByGroupID(groupId, filter);

// expect(resp).toStrictEqual({
// error: 'Activity not found for this group',
// });
// });
// });
// describe('getPostGroupById', () => {
// let app: INestApplication,
// communityService: CommunityService,
// moduleFixture: TestingModule,
// communityModel: Model<CommunityDocument>;

// beforeEach(async () => {
// moduleFixture = await Test.createTestingModule({
// imports: [AppModule],
// })
// .overrideProvider(FirebaseAdminService)
// .useValue({
// uploadFile: jest.fn(() => {
// return Promise.resolve(['https://subdomain.domain.com/name']);
// }),
// getFirebaseApp: jest.fn(() => {
// return {};
// }),
// })
// .compile();

// app = moduleFixture.createNestApplication({
// cors: true,
// bodyParser: false,
// logger: ['error'],
// });
// await app.init();
// communityService = await app.resolve<CommunityService>(CommunityService);

// communityModel = await app.get<Model<CommunityDocument>>(


// getModelToken(Community.name),
// );
// });

// afterEach(async () => {
// await communityModel.deleteMany({});
// await app.close();
// });

// it('should return error when group not found', async () => {


// const groupId = 'groupId';
// const postId = 'postId';

// when(jest.spyOn(communityModel, 'findById'))
// .calledWith(groupId)
// .mockResolvedValue(null);

// const resp = await communityService.getPostGroupById(groupId, postId);


// expect(resp).toStrictEqual({ error: 'Group not found' });
// });
// it('should return error when post not found', async () => {
// const groupId = 'groupId';
// const postId = 'postId';
// const communityId = 'communityId';
// //find group
// const group = {
// id: communityId,
// post: [],
// };
// when(jest.spyOn(communityModel, 'findById'))
// .calledWith(groupId)
// .mockResolvedValue(group);

// const resp = await communityService.getPostGroupById(groupId, postId);


// expect(resp).toStrictEqual({ error: 'Post not found' });
// });
// it('should successfully return post', async () => {
// const groupId = 'id';
// const postId = 'id';
// const communityId = 'id';

// //find group
// when(jest.spyOn(communityModel, 'findById'))
// .calledWith(groupId)
// .mockResolvedValue(getCommunityModelMock(communityId));

// const resp = await communityService.getPostGroupById(groupId, postId);


// expect(resp).toStrictEqual(getGroupPostMock());
// });
// });
describe('deletePostGroup', () => {
let app: INestApplication,
communityService: CommunityService,
moduleFixture: TestingModule,
communityModel: Model<CommunityDocument>;

beforeEach(async () => {
moduleFixture = await Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider(FirebaseAdminService)
.useValue({
uploadFile: jest.fn(() => {
return Promise.resolve(['https://subdomain.domain.com/name']);
}),
getFirebaseApp: jest.fn(() => {
return {};
}),
})
.compile();

app = moduleFixture.createNestApplication({
cors: true,
bodyParser: false,
logger: ['error'],
});
await app.init();
communityService = await app.resolve<CommunityService>(CommunityService);

communityModel = await app.get<Model<CommunityDocument>>(


getModelToken(Community.name),
);
});

afterEach(async () => {
await communityModel.deleteMany({});
await app.close();
});

it('should return error when group not found', async () => {


const groupId = 'groupId';
const postId = 'postId';
const email = 'email';
when(jest.spyOn(communityModel, 'findById'))
.calledWith(groupId)
.mockResolvedValue(null);
const resp = await communityService.deletePostGroup(
groupId,
postId,
email,
);
expect(resp).toStrictEqual({ error: 'Group not found' });
});
it('should return error when post not found', async () => {
const groupId = 'groupId';
const postId = 'postId';
const communityId = 'communityId';
const email = 'email';
const group = {
id: communityId,
members: [{ email: email }],
posts: [],
};
when(jest.spyOn(communityModel, 'findById'))
.calledWith(groupId)
.mockResolvedValue(group);

const resp = await communityService.deletePostGroup(


groupId,
postId,
email,
);
expect(resp).toStrictEqual({ error: 'Post not found' });
});

it('should return error when user is not the member of group', async () => {
const groupId = 'groupId';
const postId = 'postId';
const communityId = 'communityId';
const email = 'email';
const group = {
id: communityId,
members: [],
};
when(jest.spyOn(communityModel, 'findById'))
.calledWith(groupId)
.mockResolvedValue(group);

const resp = await communityService.deletePostGroup(


groupId,
postId,
email,
);
expect(resp).toStrictEqual({ error: 'You are not member of this group' });
});
it('should return error when group not found', async () => {
const groupId = 'groupId';
const postId = 'postId';
const email = 'email';
when(jest.spyOn(communityModel, 'findById'))
.calledWith(groupId)
.mockResolvedValue(null);

when(jest.spyOn(communityModel, 'updateOne'))
.calledWith({ _id: groupId }, { $pull: { posts: { _id: postId } } })
.mockResolvedValue(null);

const resp = await communityService.deletePostGroup(


groupId,
postId,
email,
);
expect(resp).toStrictEqual({ error: 'Group not found' });
});
it('should successfully delete post', async () => {
const groupId = 'groupId';
const postId = 'id';
const email = 'email';
const group = {
id: groupId,
posts: [getGroupPostMock()],
members: [{ email: 'email' }],
};
const groupAfterDeletePost = {
id: groupId,
posts: [],
members: [{ email: 'email' }],
};

when(jest.spyOn(communityModel, 'findById'))
.calledWith(groupId)
.mockResolvedValue(group);
when(jest.spyOn(communityModel, 'updateOne'))
.calledWith({ _id: groupId }, { $pull: { posts: { _id: postId } } })
.mockResolvedValue(groupAfterDeletePost);

const resp = await communityService.deletePostGroup(


groupId,
postId,
email,
);
expect(resp).toStrictEqual({ message: 'Post deleted successfully' });
});
});
function getCommunityModelMock(id: string) {
return {
id: id,
name: 'Padel Boiz',
description: 'Padeling with the boiz',
center: {
name: 'Rocket Padel BPS London Battersea Power Station',
centerId: 'n8T0bz1PtMa1WhVElJ7Eclg0ooj2',
},
loc: {
type: 'Point',
coordinates: [-0.1448755941600371, 51.481757964945025],
},
groupLocation: {
name: 'Nine Elms, London, UK',
place_id: 'ChIJX8pjX_oEdkgRGbrA1rI1OOY',
country: 'United Kingdom',
distance: '6.7 km',
lat: 51.481757964945025,
lng: -0.1448755941600371,
},
groupType: 'PRIVATE',
backgroundImage:
'https://firebasestorage.googleapis.com:443/v0/b/padel-mates-
e1167.appspot.com/o/E70CD81A-029D-479D-8162-6BCF85FB01F1.jpg?
alt=media&token=e64d3f64-3c13-4ec2-bb14-1248d269fbc7',
groupTopic: ['Matches'],
gameType: 'Padel',
members: [
{
name: 'Harry Wyn Jones',
email: '[email protected]',
punctuality: 0,
count: 0,
isCoach: false,
pro: false,
role: 'admin',
},
],
invites: [],
requests: [],
categories: [],
posts: [getGroupPostMock()],
};
}
function getActivityModelMock(id: string) {
return {
groupId: id,
date: '28 Nov, 2023',
time: '21:00',
gameType: 'padel',
clubInfo: { clubId: '64982d6e4759fdbbc0499c6b', clubName: 'US Padel ' },
level: [
{ name: 'name1', img: 114, im: 1, des: 'des1', point: 100 },
{ name: 'name10', img: 132, im: 10, point: 1000, des: 'des10' },
],
timeEnd: '23:00',
timeEndReal: '23:00',
dateStamp: 1688108400000,
selectedTimeEndStamp: 1687716035000,
selectedTimeStamp: 1687709135048,
locations: 'US Padel ',
public: false,
private: false,
comments: '',
isSingle: false,
friendly: false,
coordinates: { lat: 37.785834, long: '-122.406417' },
selectedpayment: 'swish',
amount: '',
silent: false,
totalAmount: '',
selectedCurrency: [{ cc: 'SEK', name: 'Swedish krona' }],
currency: 'SEK',
selectedPercentage: 30,
amountCenter: null,
number: '123456789',
calId: '',
new: true,
pro: false,
timeStampReal: 1688148000000,
player1: {
profilePic: 'https://uploads.padelmates.co/images/tes645321t',
name: 'name1',
fcmToken: '123ag',
level: { name: 'name1.5', im: 1.5, des: 'des1.5' },
points: 150,
pro: false,
count: 0,
points_Notneeded: 0,
points_needed: 0,
ava: 10,
ser: 0,
pun: 0,
availability: '',
punctuality: '',
seriousness: '',
email: '[email protected]',
lang: 'en',
},
player2: {
profilePic: 'https://uploads.padelmates.co/images/123411243',
name: 'name2',
fcmToken: '123222ag',
level: { name: 'name1.5', im: 1.5, des: 'des1.5' },
points: 150,
pro: false,
count: 0,
points_Notneeded: 0,
points_needed: 0,
ava: 10,
ser: 0,
pun: 0,
availability: '',
punctuality: '',
seriousness: '',
email: '[email protected]',
lang: 'en',
},
player3: {
name: 'name3',
email: '[email protected]',
fcmToken: 'asddas',
profilePic: 'https://uploads.padelmates.co/images/test',
level: { name: 'name4.5', im: 4.5, des: 'des4.5' },
points: 450,
pro: true,
count: 0,
ava: 0,
pun: 0,
lang: 'sw',
position: 'player3',
userId: '5f88ca16579d530004a4a1ab',
},
player4: {
profilePic: 'https://uploads.padelmates.co/images/te123231st',
name: 'pl3',
email: '[email protected]',
fcmToken: 'xtcfyvgubh',
level: { name: 'name4.5', im: 4.5, des: 'des4.5' },
points: 450,
pro: false,
count: 0,
ava: 0,
pun: 0,
lang: 'en',
position: 'player4',
userId: '6498cdad10e43ad90083814a',
},
swished: [],
feedbackGiven: [],
email: '[email protected]',
resultStack: [],
createdAt: '2023-06-25T16:24:00.950Z',
updatedAt: '2023-06-27T14:43:20.681Z',
invitePlayer: [
{
name: 'name2123',
email: '[email protected]',
fcmToken: 'token2123',
profilePic: 'https://platform-lookaside.fbsbx.com/.jpg',
level: { name: 'name5', im: 5, des: 'des5' },
points: 500,
pro: false,
count: 0,
ava: 0,
pun: 0,
lang: 'en',
position: 'player2',
userId: '60b7d3980a15620004c07586',
},
],
sevenHoursNotification: false,
activityDate: '2023-06-30T21:00:00.000Z',
};
}

function getTournamentMock(id: string) {


return {
groupId: id,
date: '28 Nov, 2023',
name: 'Superman',
email: '[email protected]',
fcmToken:

'diiPvGNb40UIrJKMbgkWyS:APA91bGsxhwG9jdh8LeasfmHDpk1s3l6lR4FzdshMrOvchNoXQVFptIBjzs
gCOXuRkB6AZfuuVESXwrFTQ5JhiHkULVMsW-9XwizZWadVfEQYe6rkxn1ZcwUoKt_f0piN8JEgV885_Tw',
profilePic: '',
level: [
{ name: 'name3', img: 116, im: 3, des: 'des3' },
{ name: 'name4', img: 117, im: 4, des: 'des4' },
{ name: 'name5', img: 118, im: 5, des: 'des5' },
],
gameType: 'padel',
time: '17:4',
title: 'Testinb',
timeEnd: '17:4',
currency: 'SEK',
timeEndReal: '17:4',
playoff: false,
dateStamp: 1688022000000,
selectedTimeEndStamp: 1687694643376,
selectedTimeStamp: 1687694643376,
locations: 'US Padel ',
public: false,
courtArr: [{ title: '' }],
comments: '',
isSingle: false,
selectedpayment: 'payment',
amount: '',
numberOfPlayers: 4,
number: '',
bookedUser: 4,
playerSelf: false,
numberOfPoint: 32,
timeStampReal: 1688040240000,
gameCode: null,
lang: 'en',
bookedEmail: [],
levelRange: [
{ name: 'name3', img: 116, im: 3, des: 'des3' },
{ name: 'name4', img: 117, im: 4, des: 'des4' },
{ name: 'name5', img: 118, im: 5, des: 'des5' },
],
type: 'tournament',
matchType: 'americano',
numberOfRound: 8,
cancelDate: 48,
isCoach: 'false',
clubInfo: { clubId: '64982d6e4759fdbbc0499c6b', clubName: 'US Padel ' },
enableTeam: false,
swished: [],
players: [
{
name: 'joseftest',
email: '[email protected]',
profilePic: null,
lang: 'en',
fcmToken:
'c1UPe1HIIUGsmRSjB1lwpI:APA91bHo-8KSFJPPrtdJj-
emX5Fr1VaZ6pajZPuovmiueb4km0i7t_Ll8sz1VnpNwH_iHv_iVaZF48xVDr1mPNTJwdGUK_2aIyLQ8Xpl9
LwcvXZZZc4IsG6e84ClSNfcSOhsal_OU2QV',
isCoach: false,
level: { name: 'name7', im: 7, des: 'des7' },
pro: false,
userId: '64982d534759fdbbc0499bf3',
},
{
name: 'Superman',
email: '[email protected]',
profilePic: '',
punctuality: 0,
lang: 'en',
fcmToken:

'diiPvGNb40UIrJKMbgkWyS:APA91bGsxhwG9jdh8LeasfmHDpk1s3l6lR4FzdshMrOvchNoXQVFptIBjzs
gCOXuRkB6AZfuuVESXwrFTQ5JhiHkULVMsW-9XwizZWadVfEQYe6rkxn1ZcwUoKt_f0piN8JEgV885_Tw',
isCoach: false,
level: { name: 'name1.5', im: 1.5, des: 'des1.5' },
pro: false,
userId: '64982d534759fdbbc0499bf3',
},
{
name: 'Daniel Dawood',
email: '[email protected]',
profilePic:

'https://uploads.padelmates.co/images/rn_image_picker_lib_temp_da8ca376-d632-4d48-
9946-43eb37b036a2.jpg?alt=media&token=838c1b11-9895-4376-84e7-e9d55832b144',
punctuality: 0,
lang: 'sw',
fcmToken:

'dpQiS7m6SiuvMO2kQXn2j8:APA91bGAo45S00k8DRumcSMHy6WXHiIQvXBzqMMyrrTRkbguckbI4Fya369
YP6WesUcrpA65CXWdwO0PHCAjFBl5tyQpkAcpWxdT7KjAMI_lf-WBBLewJoZlZ3xMV5eSbEBIDsEgA5_H',
isCoach: false,
level: { name: 'name6.5', im: 6.5, des: 'des6.5' },
userId: '64982d534759fdbbc0499bf3',
pro: true,
},
],
chatId: '64982db14759fdbbc0499e19',
createdAt: '2023-06-25T12:06:09.937Z',
updatedAt: '2023-06-27T08:41:51.620Z',
__v: 0,
requestPlayers: [],
invitedList: [
{
name: 'Ashhad Khan',
email: '[email protected]',
fcmToken:
'cLfDsGVkf0V-
pizT1RSq2E:APA91bF2aNQcAxH_t_gvnP64QDUGdbn65z6KJ1MUej72FrsjnjZKKNMopY-
YgVm968OHL54cai3QzH56W5kR7c6T-UWDojFwdALdhAHiLWw8MIf0-k2nBMLEPPW39vNRbLoT7rJ-T6rY',
profilePic:
'https://platform-lookaside.fbsbx.com/platform/profilepic/?
asid=2074073742744741&height=100&width=100&ext=1625251989&hash=AeSq3smRm-2NmI-
Yp5I',
level: { name: 'name5', im: 5, des: 'des5' },
pro: false,
lang: 'en',
isCoach: false,
userId: '60b7d3980a15620004c07586',
},
{
name: 'Josef Badro',
email: '[email protected]',
profilePic:
'https://uploads.padelmates.co/images/F8B760ED-9AA8-4EA6-9E54-
E285BB00F9D2.jpg?alt=media&token=e8111809-4bcb-4257-ad8d-d3473d04f6df',
isCoach: false,
pro: true,
lang: 'sw',
fcmToken:
'eTLqW9OHkkdIu_WP0MTGG5:APA91bHjtTkhIcm0dSzLouG-
WH8iWXds47B_pLmlbKS5O7V_1At9mbMbFCg82zbIjUqJATMZzD3eJlUyo5dxabezNjrQvUb-PaC-
qzb76_7i8b7plAoqA-JV8B4tJ6W44R3En2XXMHn-',
punctuality: 5.6,
userId: '5f88ca16579d530004a4a1ab',
},
],
};
}
function getGroupPostMock() {
return {
name: 'name1',
email: '[email protected]',
profilePic: '',
userId: '64982b0e4759fdbbc04997e6',
type: 'POST',
subtype: 'TEXT',
data: {
message: 'Hey ',
postSubtitle: 'Askes a question in this group',
initialComments: [],
isCommented: false,
isLike: false,
totalComments: 0,
totalLikes: 0,
timeStamp: 1689013607488,
postImage: '',
postVideo: '',
},
timeStamp: '2023-07-10T18:26:48.428Z',
_id: 'id',
};
}
});

You might also like