@nestjs/mongoose#getModelToken TypeScript Examples
The following examples show how to use
@nestjs/mongoose#getModelToken.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: assignment.service.spec.ts From edu-server with MIT License | 7 votes |
describe('AssignmentService', () => {
let service: AssignmentService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AssignmentService,
{
provide: getModelToken('Assignment'),
useValue: {},
},
{
provide: getModelToken('Course'),
useValue: {},
},
],
}).compile();
service = module.get<AssignmentService>(AssignmentService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
Example #2
Source File: user.service.spec.ts From edu-server with MIT License | 6 votes |
describe('UserService', () => {
let service: any;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UserService,
{
provide: getModelToken('User'),
useValue: {},
},
{
provide: getModelToken('Course'),
useValue: {},
},
{
provide: getModelToken('Enrolled'),
useValue: {},
},
],
}).compile();
service = module.resolve<UserService>(UserService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('Testing userService after mock', () => {
//const id = new mongoose.Schema.Types.ObjectId('60bca010d17d463dd09baf9b');
it('testing get all method', () => {
expect(typeof service.getAllUser).not.toEqual(null);
});
});
});
Example #3
Source File: doubt.service.spec.ts From edu-server with MIT License | 6 votes |
describe('DoubtService', () => {
let service: any;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
DoubtService,
{
provide: getModelToken('Doubt'),
useValue: {},
},
{
provide: getModelToken('Course'),
useValue: {},
},
{
provide: getModelToken('DoubtAnswer'),
useValue: {},
},
{
provide: getModelToken('User'),
useValue: {},
},
],
}).compile();
service = module.resolve<DoubtService>(DoubtService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
Example #4
Source File: chat.service.spec.ts From edu-server with MIT License | 6 votes |
describe('ChatService', () => {
let service: ChatService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ChatService,
{
provide: getModelToken('Chat'),
useValue: {},
},
],
}).compile();
service = module.get<ChatService>(ChatService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
Example #5
Source File: app.module.ts From adminjs-nestjs with MIT License | 6 votes |
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost:27017/nest'),
AdminModule.createAdminAsync({
imports: [
MongooseSchemasModule,
],
inject: [
getModelToken('Admin'),
],
useFactory: (adminModel: Model<Admin>) => ({
adminJsOptions: {
rootPath: '/admin',
resources: [
{ resource: adminModel },
],
},
auth: {
authenticate: async (email, password) => Promise.resolve({ email: 'test' }),
cookieName: 'test',
cookiePassword: 'testPass',
},
}),
customLoader: ExpressCustomLoader,
}),
MongooseSchemasModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
Example #6
Source File: mailer.service.spec.ts From uniauth-backend with MIT License | 5 votes |
describe('MailerService', () => {
let testingModule: TestingModule;
let service: MailerService;
// let model: Model<UserDocument>;
beforeEach(async () => {
testingModule = await Test.createTestingModule({
imports: [
rootMongooseTestModule(),
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
JwtModule.register({
secret: confirmEmailTokenConstants.secret,
signOptions: { expiresIn: confirmEmailTokenConstants.expiresIn },
}),
WinstonModule.forRoot(logger.console()),
],
providers: [
MailerService,
UserService,
{
provide: getModelToken(User.name),
useValue: {
findByIdAndUpdate: jest.fn().mockResolvedValue(mockUser()),
},
},
],
}).compile();
service = testingModule.get<MailerService>(MailerService);
// model = testingModule.get<Model<UserDocument>>(getModelToken(User.name));
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('.generateJwt()', () => {
it('should be defined', () => {
expect(service.generateJwt).toBeDefined();
});
});
describe('.checkVerificationToken()', () => {
it('should be defined', () => {
expect(service.checkVerificationToken).toBeDefined();
});
});
describe('.checkPasswordResetToken()', () => {
it('should be defined', () => {
expect(service.checkPasswordResetToken).toBeDefined();
});
});
describe('.sendEmail()', () => {
it('should be defined', () => {
expect(service.sendEmail).toBeDefined();
});
});
describe('.sendPasswordResetLink()', () => {
it('should be defined', () => {
expect(service.sendPasswordResetLink).toBeDefined();
});
});
});
Example #7
Source File: mentor.controller.spec.ts From codeclannigeria-backend with MIT License | 5 votes |
describe('Mentor Controller', () => {
let controller: MentorController;
const mentorService: any = {
countSubmissions: () => 1,
notifyMenteeOfGrading: jest.fn()
};
const submissionModel: any = {
find: () => jest.fn(),
findOne: jest.fn(),
updateOne: jest.fn()
};
const req = { user: 'userId' } as any;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [MentorModule, DbTest]
})
.overrideProvider(getModelToken(Submission.modelName))
.useValue(submissionModel)
.overrideProvider(MentorService)
.useValue(mentorService)
.compile();
controller = module.get<MentorController>(MentorController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
it('should get submissions', async () => {
const submissionDto: SubmissionDto = {
id: mongoose.Types.ObjectId().toHexString(),
gradePercentage: 10,
createdAt: new Date(),
updatedAt: new Date(),
taskUrl: 'www.google.com',
mentee: { firstName: 'firstName', lastName: 'lastName', id: 'menteeId' },
mentor: { firstName: 'firstName', lastName: 'lastName', id: 'mentorId' },
task: { title: 'title', id: 'taskId' },
menteeComment: null,
mentorComment: null
};
submissionModel.find = jest.fn(() => Promise.resolve([submissionDto]));
const result = await controller.getSubmissions({ limit: 1 }, req);
expect(result.totalCount).toBe(1);
expect(result.items).toContainEqual(submissionDto);
});
describe('grad submission', () => {
const input: GradeSubmissionDto = {
gradePercentage: 10,
mentorComment: 'poor'
};
it(`should throw ${NotFoundException.name} exception`, async () => {
await expect(
controller.gradeTask('submissionId', input, req)
).rejects.toThrowError(NotFoundException);
});
it('should grade task submission', async () => {
const input: GradeSubmissionDto = {
gradePercentage: 10,
mentorComment: 'poor'
};
jest.spyOn(submissionModel, 'findOne').mockReturnValue({});
return controller.gradeTask('submissionId', input, req);
});
});
});
Example #8
Source File: user.service.spec.ts From uniauth-backend with MIT License | 5 votes |
// const mockUser = (mock?: Partial<User>): Partial<UserDocument> => ({
// name: mock.name || 'some user',
// batch: mock.batch || '19',
// branch: mock.branch || 'BCE',
// personalEmail: mock.personalEmail || '[email protected]',
// collegeEmail: mock.collegeEmail || '[email protected]',
// });
/** mocking definitions */
describe('User Service', () => {
let testingModule: TestingModule;
let service: UserService;
// let model: Model<UserDocument>;
beforeEach(async () => {
testingModule = await Test.createTestingModule({
imports: [
rootMongooseTestModule(),
MongooseModule.forFeatureAsync([
{
name: 'User',
useFactory: () => {
const schema = UserSchema;
schema.plugin(mongooseUniquevalidator);
return schema;
},
},
]),
WinstonModule.forRoot(logger.console()),
],
providers: [
UserService,
{
provide: getModelToken(User.name),
useValue: {
findOne: jest.fn().mockResolvedValue(mockUser()),
save: jest.fn().mockResolvedValue(mockUser()),
findOneAndUpdate: jest.fn().mockResolvedValue(mockUser()),
find: jest.fn().mockResolvedValue([mockUser(), mockUser()]),
},
},
],
}).compile();
service = testingModule.get<UserService>(UserService);
testingModule.get<Model<UserDocument>>(getModelToken(User.name));
});
afterEach(() => {
jest.clearAllMocks();
});
it('should be defined', async () => {
await expect(service).toBeDefined();
});
/** procedure to follow for testing individual service methods */
describe('.login()', () => {
it('should be defined', () => {
expect(service.login).toBeDefined();
});
// it('should login user into system', async () => {
// console.log(mockModel);
// });
});
});
Example #9
Source File: webhook.e2e-spec.ts From whispr with MIT License | 5 votes |
describe('webhooks', () => {
let moduleRef: TestingModule;
let app: NestFastifyApplication;
beforeAll(async () => {
moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter({ bodyLimit: 104857600 }));
await app.init();
whispService = moduleRef.get<WhispService>(WhispService);
configWebhookListener();
});
afterAll(async () => {
// delete created webhooks
try {
const webhookModel = moduleRef.get<Model<IWebhook>>(getModelToken('Webhook'));
await webhookModel.deleteMany({ url: WEBHOOK_TEST_URL }).exec();
} catch (e) {
console.warn('Could not delete created webhooks', e);
}
// delete created whisps
try {
const whispModel = moduleRef.get<Model<IWhisp>>(getModelToken('Whisp'));
await whispModel.deleteMany({ type: WHISP_TEST_TYPE }).exec();
} catch (e) {
console.warn('Could not delete created whisps', e);
}
webhookListener.close();
});
describe('webhooks', () => {
let whisp: IWhisp;
it('should create a new webhook', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: CREATE_WEBHOOK_GQL,
variables: {
webhook: {
url: WEBHOOK_TEST_URL,
events: [EventNames.WHISP_CREATED, EventNames.WHISP_DELETED, EventNames.WHISP_UPDATED],
},
},
});
expect(result.status).toBe(200);
});
it('should trigger the webhook when a whisp is created', (done) => {
setExpectedEventName(EventNames.WHISP_CREATED, done);
const input = new WhispInputType();
input.type = WHISP_TEST_TYPE;
whispService.create(input).then((whispCreateed) => {
whisp = whispCreateed;
expect(whispCreateed.readableID).toBeTruthy();
});
});
it('should trigger the webhook when a whisp is updated', (done) => {
setExpectedEventName(EventNames.WHISP_UPDATED, done);
const update = new WhispInputType();
update.description = 'UPDATED';
whispService.update(whisp.id, update).then((whispUpdated) => {
expect(whispUpdated.description).toBe('UPDATED');
});
});
it('should trigger the webhook when a whisp is deleted', (done) => {
setExpectedEventName(EventNames.WHISP_DELETED, done);
whispService.delete(whisp.id);
});
});
});
Example #10
Source File: graphql.e2e-spec.ts From whispr with MIT License | 5 votes |
describe('TagGroup', () => {
beforeAll(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleRef.createNestApplication();
await app.init();
tagGroupService = moduleRef.get<TagGroupService>(TagGroupService);
});
afterAll(async () => {
try {
const model = app.get<Model<ITagGroup>>(getModelToken('TagGroup'));
await model.deleteMany({ title: TAG_GROUP_TYPE }).exec();
} catch (err) {
console.info('Could not deleted created Tag Groups during tests', err);
}
});
describe('createTagGroup', () => {
it('should create a new tag group and return a 200', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: CREATE_TAG_GROUP_GQL,
variables: {
tagGroup: {
title: TAG_GROUP_TYPE,
},
},
});
expect(result.status).toBe(200);
createdTagGroupId = result.body.data.createTagGroup.id;
const tagGroup = await tagGroupService.findOne(createdTagGroupId);
expect(tagGroup).toBeTruthy();
});
});
describe('updateTagGroup', () => {
it('should update a new tag group and return a 200', async () => {
const NEW_TITLE = 'New Title';
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: UPDATE_TAG_GROUP_GQL,
variables: {
id: createdTagGroupId,
tagGroup: {
title: NEW_TITLE,
},
},
});
expect(result.status).toBe(200);
const tagGroup = await tagGroupService.findOne(createdTagGroupId);
expect(tagGroup.title).toEqual(NEW_TITLE);
});
});
describe('deleteTagGroup', () => {
it('should delete a new tag group and return a 200', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: DELETE_TAG_GROUP_GQL,
variables: {
id: createdTagGroupId,
},
});
expect(result.status).toBe(200);
const tagGroup = await tagGroupService.findOne(createdTagGroupId);
expect(tagGroup).toBeNull();
});
});
});
Example #11
Source File: application.service.spec.ts From uniauth-backend with MIT License | 4 votes |
describe('ApplicationService', () => {
let testingModule: TestingModule;
let service: ApplicationService;
beforeEach(async () => {
testingModule = await Test.createTestingModule({
imports: [
rootMongooseTestModule(),
MongooseModule.forFeatureAsync([
{
name: 'User',
useFactory: () => {
const schema = UserSchema;
schema.plugin(mongooseUniquevalidator);
return schema;
},
},
{
name: Application.name,
useFactory: () => {
const schema = ApplicationSchema;
schema.plugin(mongooseUniquevalidator);
return schema;
},
},
]),
WinstonModule.forRoot(logger.console()),
],
providers: [
ApplicationService,
{
provide: getModelToken(User.name),
useValue: {
findOne: jest.fn().mockResolvedValue(mockUser()),
save: jest.fn().mockResolvedValue(mockUser()),
findOneAndUpdate: jest.fn().mockResolvedValue(mockUser()),
find: jest.fn().mockResolvedValue([mockUser(), mockUser()]),
},
},
],
}).compile();
service = testingModule.get<ApplicationService>(ApplicationService);
});
afterEach(() => {
jest.clearAllMocks();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('.create()', () => {
it('should be defined', () => {
expect(service.create).toBeDefined();
});
});
describe('.findAll()', () => {
it('should be defined', () => {
expect(service.findAll).toBeDefined();
});
});
describe('.findOneById()', () => {
it('should be defined', () => {
expect(service.findOneById).toBeDefined();
});
});
describe('.findAllByOwner()', () => {
it('should be defined', () => {
expect(service.findAllByOwner).toBeDefined();
});
});
describe('.findAllByParticipant()', () => {
it('should be defined', () => {
expect(service.findAllByParticipant).toBeDefined();
});
});
describe('.pushUserIntoApplicationParticipantList()', () => {
it('should be defined', () => {
expect(service.pushUserIntoApplicationParticipantList).toBeDefined();
});
});
describe('.findOneByIdAndSecret()', () => {
it('should be defined', () => {
expect(service.findOneByIdAndSecret).toBeDefined();
});
});
});
Example #12
Source File: graphql.e2e-spec.ts From whispr with MIT License | 4 votes |
describe('Tags', () => {
let moduleRef: TestingModule;
beforeAll(async () => {
moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
tagService = moduleRef.get<TagService>(TagService);
tagGroupService = moduleRef.get<TagGroupService>(TagGroupService);
const tagGroup = await tagGroupService.create({
title: TAG_TITLE,
});
// eslint-disable-next-line no-underscore-dangle
tagGroupId = tagGroup._id;
});
afterAll(async () => {
try {
const model = moduleRef.get<Model<ITag>>(getModelToken('Tag'));
await model.deleteMany({ title: TAG_TITLE }).exec();
} catch (e) {
console.info('Could not deleted created Tag Groups during tests', e);
}
});
describe('createTag', () => {
it('should create a new tag and return a 200', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: CREATE_TAG_GQL,
variables: {
tag: {
title: TAG_TITLE,
tagGroup: {
_id: tagGroupId,
},
},
},
});
expect(result.status).toBe(200);
createdTagId = result.body.data.createTag.id;
const tag = await tagService.findOne(createdTagId);
expect(tag).toBeTruthy();
});
});
describe('updateTag', () => {
it('should update a new tag and return a 200', async () => {
const NEW_TITLE = 'New Title';
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: UPDATE_TAG_GQL,
variables: {
id: createdTagId,
tag: {
title: NEW_TITLE,
},
},
});
expect(result.status).toBe(200);
const tag = await tagService.findOne(createdTagId);
expect(tag.title).toEqual(NEW_TITLE);
});
});
describe('deleteTag', () => {
it('should delete a new tag and return a 200', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: DELETE_TAG_GQL,
variables: {
id: createdTagId,
},
});
expect(result.status).toBe(200);
const tag = await tagService.findOne(createdTagId);
expect(tag).toBeNull();
});
});
});
Example #13
Source File: whisp.service.spec.ts From whispr with MIT License | 4 votes |
describe('WhispService', () => {
let whispService: WhispService;
let whispModel: Model<IWhisp>;
const OBJECT_ID = '56cb91bdc3464f14678934ca';
beforeEach(async () => {
// function to retrieve input of the called function
const passThrough = (data) => new Promise((resolve) => {
resolve(data);
});
const moduleRef = await Test.createTestingModule({
providers: [
{
provide: getModelToken('Whisp'),
useFactory: () => ({
findOneAndUpdate: jest.fn().mockReturnThis(),
create: jest.fn().mockImplementation(passThrough),
update: jest.fn(),
aggregate: jest.fn().mockReturnThis(),
allowDiskUse: jest.fn().mockReturnThis(),
exec: jest.fn(),
}),
},
WhispService,
Logger,
{
provide: DistributionService,
useFactory: () => ({
distributeWhisp: jest.fn(() => true),
}),
},
FileService,
SequenceService,
EventService,
],
}).compile();
whispService = moduleRef.get<WhispService>(WhispService);
whispModel = moduleRef.get<Model<IWhisp>>(getModelToken('Whisp'));
});
describe('create Whisp', () => {
it('should set Timestamp when no timestamp is provided', async () => {
await whispService.create({});
expect(whispModel.create).toBeCalledWith(
expect.objectContaining({
timestamp: expect.any(Date),
}),
);
});
it('should keep custom timestamp when timestamp is provided', async () => {
const timestamp = new Date();
await whispService.create({ timestamp });
expect(whispModel.create).toBeCalledWith(
expect.objectContaining({
timestamp,
}),
);
});
it('when ttl is provided expirationDate should be generate and be equal to updated date plus ttl duration', async () => {
const timeToLive = '2min';
const expectedTimeToLiveSec = 120;
const whisp = await whispService.create({ timeToLive });
const { updated: updatedDate, expirationDate, timeToLiveSec } = whisp;
const expectedExpirationDate = new Date();
expectedExpirationDate.setSeconds(updatedDate.getSeconds() + timeToLiveSec);
expectedExpirationDate.setMilliseconds(updatedDate.getMilliseconds());
expect(expirationDate).toStrictEqual(expectedExpirationDate);
expect(timeToLiveSec).toBe(expectedTimeToLiveSec);
});
it('negative ttl are forbidden', async () => {
const timeToLive = '-2';
await expect(whispService.create({ timeToLive })).rejects.toThrow(
'time to live must be positive number of seconds or a parsable time string like 2min,1hour',
);
});
it('none time string are forbidden', async () => {
const timeToLive = 'hello';
await expect(whispService.create({ timeToLive })).rejects.toThrow(
'time to live must be positive number of seconds or a parsable time string like 2min,1hour',
);
});
it('expirationDate override ttl', async () => {
const now = new Date();
now.setSeconds(now.getSeconds() + 2);
const expirationDateField = now;
const whisp = await whispService.create({ expirationDate: expirationDateField });
const { expirationDate, timeToLiveSec } = whisp;
expect(expirationDate).toStrictEqual(expirationDateField);
expect(timeToLiveSec).toBeNull();
});
});
describe('Update Whisp', () => {
it('should update timestamp when it is provided', async () => {
const timestamp = new Date();
timestamp.setHours(timestamp.getHours() + 1);
await whispService.update(OBJECT_ID, { timestamp });
expect(whispModel.findOneAndUpdate).toBeCalledWith(
expect.anything(),
expect.objectContaining({
timestamp,
}),
expect.anything(),
);
});
it('should keep timestamp when it is not provided', async () => {
await whispService.update(OBJECT_ID, {});
expect(whispModel.findOneAndUpdate).toBeCalledWith(
expect.anything(),
expect.not.objectContaining({
timestamp: expect.any(Date),
}),
expect.anything(),
);
});
});
describe('Count Whisp', () => {
it('calls mongo aggregate with empty match and group when they are not passed as parameters', async () => {
await whispService.countWhispsGroup();
const expectedMatch = { $match: {} };
const expectedGroup = { $group: { _id: undefined, count: { $sum: 1 } } };
expect(whispModel.aggregate).toBeCalledWith([expectedMatch, expectedGroup]);
});
it('calls mongo aggregate with given match when defined', async () => {
const matchParam = [
{
applicationID: 'SMUDGE',
'data.customData.id': '503',
},
{
applicationID: 'SMUDGE',
'data.customData.id': '504',
},
];
await whispService.countWhispsGroup(matchParam, undefined);
const expectedMatch = {
$match: {
$or: [
{
applicationID: 'SMUDGE',
'data.customData.id': '503',
},
{
applicationID: 'SMUDGE',
'data.customData.id': '504',
},
],
},
};
const expectedGroup = { $group: { _id: undefined, count: { $sum: 1 } } };
expect(whispModel.aggregate).toBeCalledWith([expectedMatch, expectedGroup]);
});
it('calls mongo aggregate with given group when defined', async () => {
const groupParam = { mainGrouping: '$data.customData.id', secondaryGrouping: '$data.customData.description' };
await whispService.countWhispsGroup(undefined, groupParam);
const expectedMatch = { $match: {} };
const expectedGroup = {
$group: {
_id: {
mainGrouping: '$data.customData.id',
secondaryGrouping: '$data.customData.description',
},
count: { $sum: 1 },
},
};
expect(whispModel.aggregate).toBeCalledWith([expectedMatch, expectedGroup]);
});
it('calls mongo aggregate with given match and group when both are defined', async () => {
const matchParam = [
{
applicationID: 'SMUDGE',
'data.customData.id': '503',
},
{
applicationID: 'SMUDGE',
'data.customData.id': '504',
},
];
const groupParam = { mainGrouping: '$data.customData.id', secondaryGrouping: '$data.customData.description' };
await whispService.countWhispsGroup(matchParam, groupParam);
const expectedMatch = {
$match: {
$or: [
{
applicationID: 'SMUDGE',
'data.customData.id': '503',
},
{
applicationID: 'SMUDGE',
'data.customData.id': '504',
},
],
},
};
const expectedGroup = {
$group: {
_id: {
mainGrouping: '$data.customData.id',
secondaryGrouping: '$data.customData.description',
},
count: { $sum: 1 },
},
};
expect(whispModel.aggregate).toBeCalledWith([expectedMatch, expectedGroup]);
});
});
});
Example #14
Source File: whisp.service.int-spec.ts From whispr with MIT License | 4 votes |
describe('WhispService', () => {
let whispService: WhispService;
let whispModel: Model<IWhisp>;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
rootMongooseTestModule(),
MongooseModule.forFeature([{ name: 'Whisp', schema: whispSchema }]),
DistributionModule,
FileModule,
SequenceModule,
EventModule,
],
providers: [WhispService, Logger, DistributionService, FileService, SequenceService, EventService],
}).compile();
whispService = moduleRef.get<WhispService>(WhispService);
whispModel = moduleRef.get<Model<IWhisp>>(getModelToken('Whisp'));
await whispModel.deleteMany({});
});
afterAll(async () => {
await closeInMongodConnection();
});
describe('create Whisp', () => {
it('should set Timestamp when no timestamp is provided', async () => {
const result = await whispService.create({});
expect(result.timestamp instanceof Date).toBeTruthy();
});
it('should keep custom timestamp when timestamp is provided', async () => {
const timestamp = new Date();
const result = await whispService.create({ timestamp });
expect(result.timestamp.valueOf()).toEqual(timestamp.valueOf());
});
});
describe('Update Whisp', () => {
it('should update timestamp when it is provided', async () => {
const timestamp = new Date();
timestamp.setHours(timestamp.getHours() + 1);
const initialWhisp = await whispService.create({});
const result = await whispService.update(initialWhisp._id, { timestamp });
expect(result.timestamp.valueOf()).toEqual(timestamp.valueOf());
});
it('should keep timestamp when it is not provided', async () => {
const timestamp = new Date();
timestamp.setHours(timestamp.getHours() + 1);
const initialWhisp = await whispService.create({ timestamp });
const result = await whispService.update(initialWhisp._id, {});
expect(result.timestamp.valueOf()).toEqual(initialWhisp.timestamp.valueOf());
});
});
describe('Update Whisp', () => {
it('should correctly countWhisps based on applicationID filter', async () => {
const applicationID = 'SMUDGE';
await whispService.create({ applicationID });
await whispService.create({ applicationID });
await whispService.create({ applicationID });
const filter: Record<string, unknown>[] = [
{
applicationID: 'SMUDGE',
},
];
const result = await whispService.countWhispsGroup(filter);
expect(result.length).toBeGreaterThan(0);
expect(result[0].count.valueOf()).toEqual(3);
});
it('should correctly countWhisps with complex mongo syntax query based on applicationID filter', async () => {
await whispService.create({ applicationID: 'SMUDGE' });
await whispService.create({ applicationID: 'SPIFF' });
await whispService.create({ applicationID: 'FOO' });
const filter: Record<string, unknown>[] = [
{
applicationID: { $in: ['SMUDGE', 'FOO'] },
},
];
const result = await whispService.countWhispsGroup(filter);
expect(result.length).toBeGreaterThan(0);
expect(result[0].count.valueOf()).toEqual(2);
});
it('should correctly countWhisps with an array as filter value', async () => {
await whispService.create({ applicationID: 'SMUDGE' });
await whispService.create({ applicationID: 'SPIFF' });
await whispService.create({ applicationID: 'FOO' });
const filter: Record<string, unknown>[] = [
{
applicationID: ['SMUDGE', 'FOO'],
},
];
const result = await whispService.countWhispsGroup(filter);
expect(result.length).toBeGreaterThan(0);
expect(result[0].count.valueOf()).toEqual(2);
});
it('should correctly countWhisps based on timestamp filter', async () => {
const whispDate = '2021-07-11T08:24:11.067Z';
const timestamp = new Date(whispDate);
await whispService.create({ timestamp });
await whispService.create({ timestamp });
await whispService.create({ timestamp });
const timestampFilter: Record<string, unknown>[] = [
{
timestamp: '2021-07-11T08:24:11.067Z',
},
];
const result = await whispService.countWhispsGroup(timestampFilter);
expect(result.length).toBeGreaterThan(0);
expect(result[0].count.valueOf()).toEqual(3);
});
it('should correctly countWhisps with complex mongo syntax query (greater than date comparison)', async () => {
const date1 = new Date(2020, 1, 1);
const date2 = new Date(2019, 1, 1);
const date3 = new Date(2018, 1, 1);
await whispService.create({ timestamp: date1 });
await whispService.create({ timestamp: date1 });
await whispService.create({ timestamp: date1 });
await whispService.create({ timestamp: date2 });
await whispService.create({ timestamp: date2 });
await whispService.create({ timestamp: date2 });
await whispService.create({ timestamp: date3 });
await whispService.create({ timestamp: date3 });
await whispService.create({ timestamp: date3 });
const timestampFilter: Record<string, unknown>[] = [
{
timestamp: {
$gte: '2018-07-11T08:24:11.067Z',
},
},
];
// const timestampFilter: Record<string, unknown> = {
// timestamp: "2021-07-11T08:24:11.067Z"
// };
const result = await whispService.countWhispsGroup(timestampFilter);
// const result2 = await whispService.countWhisps(timestampFilter);
// expect(result.valueOf()).toEqual(false);
// expect(result2.valueOf()).toEqual(6);
expect(result.length).toBeGreaterThan(0);
expect(result[0].count.valueOf()).toEqual(6);
});
});
});
Example #15
Source File: pubSub.e2e-spec.ts From whispr with MIT License | 4 votes |
describe('GraphQL API Subscriptions', () => {
let whispService: WhispService;
let createdWhispId: string;
let moduleRef: TestingModule;
beforeAll(async () => {
moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
whispService = moduleRef.get<WhispService>(WhispService);
const module = await Test.createTestingModule({
imports: [PubSubModule],
}).compile();
module.get<PubSubModule>(PubSubModule);
});
afterAll(async () => {
try {
const model = moduleRef.get<Model<IWhisp>>(getModelToken('Whisp'));
await model.deleteMany({ type: WHISP_TEST_TYPE }).exec();
} catch (e) {
console.warn('Could not delete created whisps', e);
}
});
describe('Whisp creation and subscription ', () => {
let subscriptionsCount = 0;
let resultListening;
// SUBSCRIPTION
it('should fire subscription and start listening', async () => {
resultListening = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: SUBSCRIPTION_GQL,
variables: {
filter: {
type: WHISP_TEST_TYPE,
},
},
});
if (resultListening.status === 200) {
subscriptionsCount += 1;
}
expect(resultListening.status).toBe(200);
expect(subscriptionsCount).toBe(1);
});
// MUTATION
it('should create a new Whisp and return its id', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: CREATE_WHISP_GQL,
variables: {
whisp: {
type: WHISP_TEST_TYPE,
},
},
});
expect(result.status).toBe(200);
createdWhispId = result.body.data.createWhisp._id;
expect(createdWhispId).toEqual(expect.any(String));
});
describe('Whisp subscription and publishing mutation', () => {
// SUBSCRIPTION RECEIVED EVENT
it('should successfully get data from subscription after publishing mutation', async () => {
await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: SUBSCRIPTION_GQL,
variables: {
filter: {
type: WHISP_TEST_TYPE,
},
},
});
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: CREATE_WHISP_GQL,
variables: {
whisp: {
type: WHISP_TEST_TYPE,
},
},
});
createdWhispId = result.body.data.createWhisp._id;
await whispService.findOne(result.body.data.createWhisp._id);
});
});
});
});
Example #16
Source File: graphql.e2e-spec.ts From whispr with MIT License | 4 votes |
describe('Whisps', () => {
let moduleRef: TestingModule;
beforeAll(async () => {
moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
whispService = moduleRef.get<WhispService>(WhispService);
fileService = moduleRef.get<FileService>(FileService);
});
afterAll(async () => {
try {
const model = moduleRef.get<Model<IWhisp>>(getModelToken('Whisp'));
await model.deleteMany({ type: WHISP_TEST_TYPE }).exec();
} catch (e) {
console.warn('Could not delete created whisps', e);
}
});
describe('GRAPHQL WhispModule (e2e)', () => {
describe('createWhisp', () => {
it('should return a 200 and create a new Whisp and return its id', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: CREATE_WHISP_GQL,
variables: {
whisp: {
type: WHISP_TEST_TYPE,
},
},
});
expect(result.status).toBe(200);
createdWhispId = result.body.data.createWhisp._id;
expect(createdWhispId).toEqual(expect.any(String));
});
it('should keep ISO-String when a timestamp is provided', async () => {
const now = new Date();
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: CREATE_WHISP_GQL,
variables: {
whisp: {
type: WHISP_TEST_TYPE,
timestamp: now,
},
},
});
expect(result.status).toBe(200);
const createdWhispTimestamp = result.body.data.createWhisp.timestamp;
expect(createdWhispTimestamp).toEqual(now.toISOString());
});
function runFileTest(fileName: string, filePath: string, fileLength: number) {
it(`should upload ${fileName} to S3 when attached`, async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.field(
'operations',
JSON.stringify({
query: CREATE_WHISP_GQL,
variables: {
whisp: {
type: WHISP_TEST_TYPE,
attachments: [{ file: { newFile: null } }],
},
},
}),
)
.field(
'map',
JSON.stringify({
file: ['variables.whisp.attachments.0.file.newFile'],
}),
)
.attach('file', filePath);
expect(result.status).toBe(200);
const whisp = await whispService.findOne(result.body.data.createWhisp._id);
const file = await fileService.getFile(whisp.attachments[0].file);
expect(file.ContentLength).toBe(fileLength);
});
}
runFileTest('attached-file-1.png', 'tests/e2e/whisp/attached-file-1.png', 14948);
runFileTest('attached-file-2.txt', 'tests/e2e/whisp/attached-file-2.txt', 19);
});
describe('updateWhisp', () => {
it('should change any field on a whisp and return a 200', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: UPDATE_WHISP_GQL,
variables: {
id: createdWhispId,
whisp: {
description: WHISP_TEST_TYPE,
},
},
});
expect(result.status).toBe(200);
const whisp = await whispService.findOne(createdWhispId);
expect(whisp.description).toBe(WHISP_TEST_TYPE);
});
it('should preserve attachment field when not provided', async () => {
const createResult = await request(global.app.getHttpServer())
.post('/graphql')
.field(
'operations',
JSON.stringify({
query: CREATE_WHISP_GQL,
variables: {
whisp: {
type: WHISP_TEST_TYPE,
attachments: [{ file: { newFile: null } }],
},
},
}),
)
.field(
'map',
JSON.stringify({
file: ['variables.whisp.attachments.0.file.newFile'],
}),
)
.attach('file', 'tests/e2e/whisp/attached-file-1.png');
await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: UPDATE_WHISP_GQL,
variables: {
id: createResult.body.data.createWhisp._id,
whisp: {
description: WHISP_TEST_TYPE,
},
},
});
const whisp = await whispService.findOne(createResult.body.data.createWhisp._id);
expect(whisp.attachments).toHaveLength(1);
});
});
describe('deleteWhisp', () => {
it('should delete the whisp and return a 200', async () => {
const result = await request(global.app.getHttpServer())
.post('/graphql')
.send({
query: DELETE_WHISP_GQL,
variables: {
id: createdWhispId,
},
});
expect(result.status).toBe(200);
const whisp = await whispService.findOne(createdWhispId);
expect(whisp).toBeNull();
});
});
});
});
Example #17
Source File: course.service.spec.ts From edu-server with MIT License | 4 votes |
describe('CourseService', () => {
let service: CourseService;
let model: Model<CourseDoc>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CourseService,
{
provide: getModelToken('Course'),
useValue: {
new: jest.fn().mockResolvedValue(mockCourse),
constructor: jest.fn().mockResolvedValue(mockCourse),
find: jest.fn(),
populate: jest.fn(),
findOne: jest.fn(),
findById: jest.fn(),
update: jest.fn(),
create: jest.fn(),
remove: jest.fn(),
exec: jest.fn(),
findByIdAndUpdate: jest.fn(),
},
},
{
provide: getModelToken('Schedule'),
useValue: {},
},
{
provide: getModelToken('Review'),
useValue: {},
},
{
provide: getModelToken('Doubt'),
useValue: {},
},
{
provide: getModelToken('DoubtAnswer'),
useValue: {},
},
{
provide: getModelToken('Assignment'),
useValue: {},
},
{
provide: getModelToken('Lecture'),
useValue: {},
},
{
provide: getModelToken('Mentor'),
useValue: {},
},
],
}).compile();
service = module.get<CourseService>(CourseService);
model = module.get<Model<CourseDoc>>(getModelToken('Course'));
});
it('should be defined', () => {
expect(service).toBeDefined();
});
beforeEach(() => {
jest.setTimeout(25000);
});
afterEach(() => {
jest.setTimeout(5000);
jest.clearAllMocks();
});
describe('Testing courseservice after mock', () => {
const _id = '60bca010d17d463dd09baf9b';
const courseDocArray = [mockCourseDoc({}, _id)];
// Test for testing the service for returning all courses
it('should return all courses', async () => {
jest.spyOn(model, 'find').mockReturnValue({
exec: jest.fn().mockResolvedValueOnce(courseDocArray),
} as any);
const courses = await service.findAllCourses();
const courseArray = [{ ...mockCourse(), _id }];
expect(courses).toEqual(courseArray);
});
// Test for testing the service for finding a Course by id
it('should getOne Course by id', async () => {
jest.spyOn(model, 'findById').mockReturnValueOnce(
createMock<Query<CourseDoc, CourseDoc>>({
exec: jest.fn().mockResolvedValueOnce(mockCourseDoc()),
}),
);
const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex');
const findMockCourse = {
...mockCourse(),
_id: '6079f573062890a5e2cad207',
};
const foundCourse = await service.findCourseDummy(id);
expect(foundCourse).toEqual(findMockCourse);
});
// Test for testing the service for updating a Course
it('should update a Course successfully', async () => {
jest.spyOn(model, 'findByIdAndUpdate').mockReturnValueOnce(
createMock<Query<CourseDoc, CourseDoc>>({
exec: jest.fn().mockResolvedValueOnce({
name: 'DSA with JAVA',
originalPrice: 100,
active: false,
couponCode: 'CFC424',
video_num: 0,
duration: '11.5 hours',
assignments: [],
start_date: '2020-02-05T06:35:22.000Z',
end_date: '2020-02-05T06:35:22.000Z',
sharable_link: 'https://java.com',
mentor: [],
tags: [TagType.WEB_DEV],
courseDetails:
'The course gives a hands on learning experience on Rest APIs and Javascript',
courseLevel: courseLevelType.BEGINNER,
courseThumbnail: 'https://codeforcause.org/courses',
courseTrailerUrl: 'https://codeforcause.org/courseTrailer',
no_of_enrollments: 1000,
student_num: 2,
schedule: [],
reviews: [],
doubts: [],
_id: '6079f573062890a5e2cad207',
crossPrice: 120,
courseShortDescription: 'Short description--',
courseLongDescription: 'Long description--',
rating: 5,
prerequisites: [],
skills: [],
whatYouWillLearn: [],
certificateUrl: 'https://codeforcause.org/certificate',
isUpcoming: false,
}),
}),
);
const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex');
const updateCoursedto: UpdateCourseDTO = {
name: 'DSA with JAVA',
originalPrice: 100,
active: false,
couponCode: 'CFC424',
video_num: 0,
duration: '11.5 hours',
start_date: new Date('2020-02-05T06:35:22.000Z'),
end_date: new Date('2020-02-05T06:35:22.000Z'),
sharable_link: 'https://java.com',
tags: [TagType.WEB_DEV],
courseDetails:
'The course gives a hands on learning experience on Rest APIs and Javascript',
courseLevel: courseLevelType.BEGINNER,
courseThumbnail: 'https://codeforcause.org/courses',
courseTrailerUrl: 'https://codeforcause.org/courseTrailer',
no_of_enrollments: 1000,
crossPrice: 120,
courseShortDescription: 'Short description--',
courseLongDescription: 'Long description--',
rating: 5,
prerequisites: [],
skills: [],
whatYouWillLearn: [],
certificateUrl: 'https://codeforcause.org/certificate',
isUpcoming: false,
};
const updatedCourse = await service.editCourse(id, updateCoursedto);
const _id = '6079f573062890a5e2cad207';
const updatedCourseFinal = { ...mockCourse(), ...updatedCourse, _id };
expect(updatedCourse).toEqual(updatedCourseFinal);
});
});
});
Example #18
Source File: mentor.service.spec.ts From edu-server with MIT License | 4 votes |
describe('MentorService', () => {
let service: MentorService;
let model: Model<MentorDoc>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
MentorService,
{
provide: getModelToken('Mentor'),
useValue: {
new: jest.fn().mockResolvedValue(mockMentor),
constructor: jest.fn().mockResolvedValue(mockMentor),
find: jest.fn(),
populate: jest.fn(),
findOne: jest.fn(),
findById: jest.fn(),
update: jest.fn(),
create: jest.fn(),
remove: jest.fn(),
exec: jest.fn(),
findByIdAndUpdate: jest.fn(),
},
},
{
provide: getModelToken('Course'),
useValue: {},
},
],
}).compile();
service = module.get<MentorService>(MentorService);
model = module.get<Model<MentorDoc>>(getModelToken('Mentor'));
});
it('should be defined', () => {
expect(service).toBeDefined();
});
beforeEach(() => {
jest.setTimeout(10000);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('Testing MentorService after mock', () => {
const _id = '60bca010d17d463dd09baf9b';
const mentorDocArray = [mockMentorDoc({}, _id)];
// Test for testing the service for returning all mentors
it('should return all mentors', async () => {
jest.spyOn(model, 'find').mockReturnValue({
exec: jest.fn().mockResolvedValueOnce(mentorDocArray),
} as any);
// console.log(mentorDocArray);
const mentors = await service.getAllMentor();
// console.log(mentors);
const mentorArray = [{ ...mockMentor(), _id }];
expect(mentors).toEqual(mentorArray);
});
// Test for testing the service for finding a Mentor by id
it('should getOne Mentor by id', async () => {
jest.spyOn(model, 'findById').mockReturnValueOnce(
createMock<Query<MentorDoc, MentorDoc>>({
exec: jest.fn().mockResolvedValueOnce(mockMentorDoc()),
}),
);
const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex');
const findMockMentor = {
...mockMentor(),
_id: '6079f573062890a5e2cad207',
};
const foundMentor = await service.findMentorById(id);
expect(foundMentor).toEqual(findMockMentor);
});
// Test for testing the service for updating a Mentor
it('should update a Mentor successfully', async () => {
jest.spyOn(model, 'findByIdAndUpdate').mockReturnValueOnce(
createMock<Query<MentorDoc, MentorDoc>>({
exec: jest.fn().mockResolvedValueOnce({
_id: '6079f573062890a5e2cad207',
name: 'Abhishek Kumar',
email: '[email protected]',
courses: [],
number_of_students: 100000,
mentorPhoto: 'https://codeforcause.org/static/images',
aboutMe: 'I am a full stack developer',
techStack: ['MERN', 'Java', 'Python'],
}),
}),
);
const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex');
const updatedMentordto: UpdateMentorDTO = {
name: 'Abhishek Kumar',
email: '[email protected]',
number_of_students: 100000,
mentorPhoto: 'https://codeforcause.org/static/images',
aboutMe: 'I am a full stack developer',
techStack: ['MERN', 'Java', 'Python'],
};
const updatedMentor = await service.updateMentor(id, updatedMentordto);
const _id = '6079f573062890a5e2cad207';
const updatedMentorFinal = { ...mockMentor(), ...updatedMentor, _id };
expect(updatedMentor).toEqual(updatedMentorFinal);
});
});
});