Skip to content

Commit

Permalink
test: increase coverage for signal service
Browse files Browse the repository at this point in the history
  • Loading branch information
PhearZero committed Apr 27, 2024
1 parent a72d72d commit 71d200a
Show file tree
Hide file tree
Showing 5 changed files with 150 additions and 78 deletions.
4 changes: 1 addition & 3 deletions services/liquid-auth-api-js/src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@ describe('AuthController', () => {

const session = new Session();

await expect(authController.keys(session)).rejects.toThrow(
InternalServerErrorException,
);
await expect(authController.keys(session)).rejects.toThrow();
});
});

Expand Down
35 changes: 13 additions & 22 deletions services/liquid-auth-api-js/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ import type { Response } from 'express';
import { AuthService } from './auth.service.js';
import { AuthGuard } from './auth.guard.js';
import {
ApiResponse,
ApiForbiddenResponse,
ApiCookieAuth,
ApiForbiddenResponse,
ApiOperation,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { User } from './auth.schema.js';
Expand All @@ -40,14 +40,7 @@ export class AuthController {
@UseGuards(AuthGuard)
async keys(@Session() session: Record<string, any>) {
const wallet = session.wallet;
try {
const user = await this.authService.find(wallet);
return user || {};
} catch (e) {
throw new InternalServerErrorException({
error: e.message,
});
}
return await this.authService.find(wallet);
}
/**
* Delete Credential
Expand Down Expand Up @@ -104,17 +97,15 @@ export class AuthController {
@ApiOperation({ summary: 'Get Session' })
async read(@Session() session: Record<string, any>) {
const user = await this.authService.find(session.wallet);
return (
{
user: user
? {
id: user.id,
wallet: user.wallet,
credentials: user.credentials,
}
: null,
session,
} || {}
);
return {
user: user
? {
id: user.id,
wallet: user.wallet,
credentials: user.credentials,
}
: null,
session,
};
}
}
3 changes: 3 additions & 0 deletions services/liquid-auth-api-js/src/config/configuration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ import configFactory from './configuration.js';
import configFixture from '../__fixtures__/configuration.fixture.json';
describe('configuration', () => {
it('should return the configuration', () => {
delete process.env.NODE_ENV;
expect(configFactory()).toEqual({
...configFixture,
env: 'development',
hostname: 'localhost',
origin: 'http://localhost',
});
process.env.NODE_ENV = 'test';
});
});
131 changes: 106 additions & 25 deletions services/liquid-auth-api-js/src/signals/signals.gateway.spec.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,55 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SignalsGateway } from './signals.gateway.js';
import { SignalsGateway, reloadSession } from './signals.gateway.js';
import { Server, Socket } from 'socket.io';
import mongoose, { Model } from 'mongoose';
import { User, UserSchema } from '../auth/auth.schema.js';
import { AuthService } from '../auth/auth.service.js';
import { getModelToken } from '@nestjs/mongoose';
import { mockAuthService } from '../__mocks__/auth.service.mock.js';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const candidateFixture = require('./__fixtures__/candidate.fixture.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const sdpFixtures = require('./__fixtures__/sdp.fixtures.json');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const sessionFixtures = require('../__fixtures__/session.fixtures.json');
import candidateFixture from './__fixtures__/candidate.fixture.json';
import sdpFixtures from './__fixtures__/sdp.fixtures.json';
import sessionFixtures from '../__fixtures__/session.fixtures.json';
import { Session } from 'express-session';

const clientFixture = {
const clientMock = {
request: {
session: sessionFixtures.authorized,
},
rooms: new Set(),
join: jest.fn(),
} as unknown as Socket;

let linkEventFn: any;
const ioAdapterMock = {
subClient: {
on: jest.fn((name: string, fn) => {
linkEventFn = fn;
}),
off: jest.fn(),
subscribe: jest.fn(),
},
};
jest.mock('socket.io', () => {
return {
Server: jest.fn().mockImplementation(() => {
return {
emit: jest.fn(),
in: jest.fn().mockReturnThis(),
sockets: {
adapter: ioAdapterMock,
},
};
}),
};
});

describe.skip('SignalsGateway', () => {
describe('SignalsGateway', () => {
let gateway: SignalsGateway;
let userModel: Model<User>;
beforeEach(async () => {
userModel = mongoose.model('User', UserSchema);
// TODO: Session Mock
Object.keys(sessionFixtures).forEach((key) => {
sessionFixtures[key].reload = jest.fn(async () => {});
sessionFixtures[key].reload = jest.fn(async (fn) => fn(null));
});

const module: TestingModule = await Test.createTestingModule({
Expand All @@ -49,53 +60,123 @@ describe.skip('SignalsGateway', () => {
},
{
provide: AuthService,
useValue: { ...mockAuthService },
useValue: {
...mockAuthService,
findSession: jest
.fn()
.mockResolvedValue(sessionFixtures.authorized),
updateSessionWallet: jest
.fn()
.mockResolvedValue(sessionFixtures.authorized),
},
},
SignalsGateway,
],
}).compile();

gateway = module.get<SignalsGateway>(SignalsGateway);
gateway.server = new Server();
// @ts-expect-error, testing purposes
gateway.logger.debug = jest.fn();
// @ts-expect-error, testing purposes
gateway.ioAdapter = ioAdapterMock;
});
it('should be defined', () => {
expect(gateway).toBeDefined();
});
it('should add the ioAdapter after init', () => {
gateway.afterInit(gateway.server);
// @ts-expect-error, testing purposes
expect(gateway.ioAdapter).toBeInstanceOf(Object);
});
it('should handle a authenticated connection', async () => {
await gateway.handleConnection(clientMock);
expect(clientMock.join).toHaveBeenCalledWith(
sessionFixtures.authorized.wallet,
);
});
it('should handle a unauthenticated connection', async () => {
await gateway.handleConnection({
request: {
session: sessionFixtures.unauthorized,
},
} as unknown as Socket);
// @ts-expect-error, testing purposes
expect(gateway.logger.debug).toHaveBeenCalled();
});
it('should signal a offer-description', () => {
gateway.onCallDescription(sdpFixtures.call, clientFixture);
it('should log a disconnect', async () => {
gateway.handleDisconnect(clientMock);
// @ts-expect-error, testing purposes
expect(gateway.logger.debug).toHaveBeenCalled();
});
it('should handle a link event', async () => {
await gateway.link({ requestId: 0.1 }, clientMock);
expect(clientMock.join).toHaveBeenCalledWith(
sessionFixtures.authorized.wallet,
);
expect(globalThis.handleObserver).toBeInstanceOf(Function);
expect(
globalThis.handleObserver({ next: jest.fn(), complete: jest.fn() }),
).toBeUndefined();
expect(
linkEventFn(null, JSON.stringify({ data: { requestId: 0.1 } })),
).resolves.toBeUndefined();
expect(globalThis.handleObserverMap).toBeInstanceOf(Function);
expect(
globalThis.handleObserverMap({
credId: '0.1',
requestId: 0.1,
wallet: '0.1',
}),
).toStrictEqual({ data: { credId: '0.1', requestId: 0.1, wallet: '0.1' } });
});
it('should signal a offer-description', async () => {
await gateway.onOfferDescription(sdpFixtures.call, clientMock);
expect(gateway.server.in).toHaveBeenCalledWith(
(clientFixture.request as any).session.wallet,
(clientMock.request as any).session.wallet,
);
expect(gateway.server.emit).toHaveBeenCalledWith(
'offer-description',
sdpFixtures.call,
);
});
it('should signal a offer-candidate', () => {
gateway.onCallCandidate(candidateFixture, clientFixture);
it('should signal a offer-candidate', async () => {
await gateway.onOfferCandidate(candidateFixture, clientMock);
expect(gateway.server.in).toHaveBeenCalledWith(
(clientFixture.request as any).session.wallet,
(clientMock.request as any).session.wallet,
);
expect(gateway.server.emit).toHaveBeenCalledWith(
'offer-candidate',
candidateFixture,
);
});
it('should signal a answer-description', () => {
gateway.onAnswerDescription(sdpFixtures.answer, clientFixture);
it('should signal a answer-description', async () => {
await gateway.onAnswerDescription(sdpFixtures.answer, clientMock);
expect(gateway.server.in).toHaveBeenCalledWith(
(clientFixture.request as any).session.wallet,
(clientMock.request as any).session.wallet,
);
expect(gateway.server.emit).toHaveBeenCalledWith(
'answer-description',
sdpFixtures.answer,
);
});
it('should signal a answer-candidate', () => {
gateway.onAnswerCandidate(candidateFixture, clientFixture);
it('should signal a answer-candidate', async () => {
await gateway.onAnswerCandidate(candidateFixture, clientMock);
expect(gateway.server.in).toHaveBeenCalledWith(
(clientFixture.request as any).session.wallet,
(clientMock.request as any).session.wallet,
);
expect(gateway.server.emit).toHaveBeenCalledWith(
'answer-candidate',
candidateFixture,
);
});
it('should reject a failed session reload', async () => {
//@ts-expect-error, testing purposes
sessionFixtures.authorized.reload = jest.fn(async (fn) =>
fn(new Error('failed')),
);
await expect(
reloadSession(sessionFixtures.authorized as unknown as Session),
).rejects.toThrowError('failed');
});
});
Loading

0 comments on commit 71d200a

Please sign in to comment.