Skip to content

Commit

Permalink
added test case for user controller
Browse files Browse the repository at this point in the history
  • Loading branch information
varsha766 committed Nov 14, 2023
1 parent e8a7f1d commit 7b47a68
Show file tree
Hide file tree
Showing 5 changed files with 145 additions and 74 deletions.
53 changes: 49 additions & 4 deletions src/app-auth/controllers/app-auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,63 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppAuthController } from './app-auth.controller';
import { AppAuthService } from '../services/app-auth.service';

describe('AppAuthController', () => {
let controller: AppAuthController;
const mockApp = {
appName: 'new fyre app',
appId: '3977ed2d3c26824d77c08c24aa7f22dbee81',
edvId: 'hs:studio-api:app:3977ed2d3c26824d77c08c24aa7f22dbee81',
walletAddress: 'hid1yam5kyrcyvrpah750zfhsjuqg5u2lfc3th2wul',
whitelistedCors: ['*', 'http://locahost:8080'],
logoUrl: '',
subdomain: 'ent_5f9e3e0',
tenantUrl: 'http://ent_5f9e3e0.localhost:8080',
};
const findAppResp = [
{
totalCount: 1,
data: [mockApp],
},
];

const createAppResp = {
appName: 'new fyre app',
appId: '3977ed2d3c26824d77c08c24aa7f22dbee81',
edvId: 'hs:studio-api:app:3977ed2d3c26824d77c08c24aa7f22dbee81',
kmsId: 'hs:doc:vnc7vkyvhfmcr3hsp450cxtyunlcnappu4m2ef3kmgi',
walletAddress: 'hid1yam5kyrcyvrpah750zfhsjuqg5u2lfc3th2wul',
whitelistedCors: ['*', 'http://locahost:8080'],
logoUrl: '',
subdomain: 'ent_5f9e3e0',
apiSecretKey:
'db1ee5a1282b2f03da1c1b6c2dc6e.66bff8a7785a6e171cde95c4f9f9f7e926ca76b3688d9622e320062c4749aca1d569de5fffc5bfd6773e57542b4677d4d',
tenantUrl: 'http://ent_5f9e3e0.localhost:8080/',
};

describe('AppAuthController', () => {
let appAuthcontroller: AppAuthController;
let spyAppAuthService: AppAuthService;
beforeEach(async () => {
const AppAuthProvider = {
provide: AppAuthService,
useFactory: () => ({
getAllApps: jest.fn().mockResolvedValue(findAppResp),
getAppById: jest.fn().mockResolvedValue(mockApp),
createAnApp: jest.fn().mockResolvedValue(createAppResp),
updateAnApp: jest.fn().mockResolvedValue(mockApp),
deleteApp: jest.fn().mockResolvedValue(mockApp),
reGenerateAppSecretKey: jest.fn().mockResolvedValue(mockApp),
}),
};
const module: TestingModule = await Test.createTestingModule({
controllers: [AppAuthController],
providers: [AppAuthService],
}).compile();

controller = module.get<AppAuthController>(AppAuthController);
appAuthcontroller = module.get<AppAuthController>(AppAuthController);
spyAppAuthService = module.get<AppAuthService>(AppAuthService);
});

it('should be defined', () => {
expect(controller).toBeDefined();
expect(appAuthcontroller).toBeDefined();
});
});
3 changes: 0 additions & 3 deletions src/app-auth/controllers/app-auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
HttpCode,
UseFilters,
Query,
UseGuards,
Req,
Delete,
Logger,
Expand All @@ -35,8 +34,6 @@ import { AllExceptionsFilter } from '../../utils/utils';
import { AppError, GetAppList } from '../dtos/fetch-app.dto';
import { PaginationDto } from 'src/utils/pagination.dto';
import { TransformResponseInterceptor } from '../interceptors/transformResponse.interseptor';
import { AuthenticatedGuard } from 'src/org-user/guard/authenticated.guard';

@UseFilters(AllExceptionsFilter)
@ApiTags('Application')
@Controller('/api/v1/app')
Expand Down
26 changes: 0 additions & 26 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,8 @@ import { EdvClientKeysManager } from './edv/services/edv.singleton';
import { VaultWalletManager } from './edv/services/vaultWalletManager';
import { AppAuthModule } from './app-auth/app-auth.module';
import { AppOauthModule } from './app-oauth/app-oauth.module';
import { OrgUserModule } from './org-user/org-user.module';
//import { Header } from '@nestjs/common';
import * as cors from 'cors';

import * as session from 'express-session';
import * as passport from 'passport';
import { UserModule } from './user/user.module';

// eslint-disable-next-line
Expand Down Expand Up @@ -63,8 +59,6 @@ async function bootstrap() {
const kmsVaultWallet = await VaultWalletManager.getWallet(
mnemonic_EnglishMnemonic,
);

// app.setGlobalPrefix('api/v1');
if (!existDir(process.env.EDV_CONFIG_DIR)) {
createDir(process.env.EDV_CONFIG_DIR);
}
Expand Down Expand Up @@ -108,26 +102,6 @@ async function bootstrap() {
.setVersion('1.0')
.build();

// const tenantDocConfig = new DocumentBuilder()
// .setTitle('Entity Studio SSI API Playground')
// .setDescription('Open API Documentation of the Entity Studio')
// .addBearerAuth(
// {
// type: 'http',
// name: 'Authorization',
// in: 'header',
// },
// 'Authorization',
// )
// .setVersion('1.0')
// .build();

// const tenantDocuments = SwaggerModule.createDocument(app, tenantDocConfig, {
// include: [
// AppOauthModule,

// ], // don't include, say, BearsModule
// });
const orgDocuments = SwaggerModule.createDocument(app, orgDocConfig, {
include: [AppAuthModule, AppOauthModule, UserModule], // don't include, say, BearsModule
});
Expand Down
103 changes: 92 additions & 11 deletions src/user/controllers/user.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,99 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserController } from './user.controller';

import { UserService } from '../services/user.service';
import { UserRepository } from '../repository/user.repository';
const mockUser = {
_id: '641d2e711f35ed7575931',
email: 'varshakumari370@gmail.com',
userId: 'ab8d48e0-60eb-437c-9a86-e063080b2943',
did: 'did:hid:testnet:z2JFAEgfG5b7PhjHmCGuAeRPzqUaJ3Te9LUycbDMRzDwH',
createdAt: '2023-11-13T15:24:49.053Z',
updatedAt: '2023-11-13T15:24:49.053Z',
};
const reqBody = {
hypersign: {
data: {
user: {
email: 'varshakumari370@gmail.com',
appUserID: 'ab8d48e0-60eb-437c-9a86-e063080b2943',
did: 'did:hid:testnet:z2JFAEgfG5b7PhjHmCGuAeRPzqUaJ3Te9LUycbDMRzDwH',
},
},
},
};
const authenticateResp = {
error: null,
message: {
email: 'varshakumari370@gmail.com',
appUserID: 'ab8d48e0-60eb-437c-9a86-e063080b2943',
did: 'did:hid:testnet:z2JFAEgfG5b7PhjHmCGuAeRPzqUaJ3Te9LUycbDMRzDwH',
},
status: 200,
};
const authorizeResp = {
...authenticateResp,
message: {
user: {
email: 'varshakumari370@gmail.com',
appUserID: 'ab8d48e0-60eb-437c-9a86-e063080b2943',
did: 'did:hid:testnet:z2JFAEgfG5b7PhjHmCGuAeRPzqUaJ3Te9LUycbDMRzDwH',
},
},
};
describe('UserController', () => {
let controller: UserController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
}).compile();

controller = module.get<UserController>(UserController);
let userController: UserController;
let spyUserService: UserService;
describe('authenticate() method', () => {
it('should be register new user', async () => {
const mockFindOneUser = jest.fn().mockResolvedValue({});
const createAUser = jest.fn().mockResolvedValue(mockUser);
const userRepository = {
findOne: mockFindOneUser,
create: createAUser,
};
const userModule: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [
UserRepository,
{ provide: UserRepository, useValue: userRepository },
],
}).compile();
userController = userModule.get<UserController>(UserController);
const req = {};
const res = {
status: jest.fn(() => res),
json: jest.fn(),
};
await userController.authenticate(res, req, reqBody);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(authenticateResp);
});
});
describe('authorize() method', () => {
it('should be able to authorize a user and get user inforamtion as response', async () => {
const mockFindOneUser = jest.fn().mockResolvedValue({});
const createAUser = jest.fn().mockResolvedValue(mockUser);
const userRepository = {
findOne: mockFindOneUser,
create: createAUser,
};
const userModule: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [
UserRepository,
{ provide: UserRepository, useValue: userRepository },
],
}).compile();
userController = userModule.get<UserController>(UserController);
const req = {};
const res = {
status: jest.fn(() => res),
json: jest.fn(),
};

it('should be defined', () => {
expect(controller).toBeDefined();
await userController.authorize(res, req, reqBody);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(authorizeResp);
});
});
});
34 changes: 4 additions & 30 deletions src/user/controllers/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,30 @@
import {
Controller,
Get,
ValidationPipe,
Post,
UsePipes,
Body,
Put,
Param,
UseInterceptors,
HttpCode,
UseFilters,
Query,
UseGuards,
Req,
Delete,
Logger,
Res,
Req,
} from '@nestjs/common';
import { CreateAppDto } from 'src/app-auth/dtos/create-app.dto';
import { AppAuthService } from 'src/app-auth/services/app-auth.service';
import {
ApiBadRequestResponse,
ApiCreatedResponse,
ApiNotFoundResponse,
ApiQuery,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { AppNotFoundException } from 'src/app-auth/exceptions/app-not-found.exception';
import { MongooseClassSerializerInterceptor } from '../../utils/utils';

import { ApiTags } from '@nestjs/swagger';
import { AllExceptionsFilter } from '../../utils/utils';
import { PaginationDto } from 'src/utils/pagination.dto';
import { AuthenticatedGuard } from 'src/org-user/guard/authenticated.guard';
import { UserService } from '../services/user.service';
import { UserRepository } from '../repository/user.repository';

@UseFilters(AllExceptionsFilter)
@ApiTags('Authentication')
@Controller()
export class UserController {
constructor(
private readonly userService: UserService,
private readonly userRepository: UserRepository,
) {}
constructor(private readonly userRepository: UserRepository) {}

@Post('/hs/api/v2/auth')
@UsePipes(new ValidationPipe({ transform: true }))
async authenticate(@Res() res: any, @Req() req: any, @Body() body: any) {
Logger.log('authenticate() method: starts', 'userController');

const { hypersign } = body;
Logger.log(hypersign);
const { user } = hypersign.data;
let userInfo = await this.userRepository.findOne({ email: user.email });
if (!userInfo) {
Expand Down

0 comments on commit 7b47a68

Please sign in to comment.