56 lines
1.9 KiB
TypeScript
56 lines
1.9 KiB
TypeScript
import { ExecutionContext } from '@nestjs/common';
|
|
import mongoose from 'mongoose';
|
|
import { ConnectionService } from '../global/database/connection.service';
|
|
import { IdentityDocument, UserDocument } from '../global/database/schema';
|
|
import { UserResolverGuard } from './user-resolver.guard';
|
|
import './auth-request';
|
|
|
|
function createContext(request: Record<string, unknown>): ExecutionContext {
|
|
return {
|
|
switchToHttp: () => ({
|
|
getRequest: () => request,
|
|
}),
|
|
} as ExecutionContext;
|
|
}
|
|
|
|
describe('UserResolverGuard', () => {
|
|
it('resolves the community membership before role guards run', async () => {
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const identityId = new mongoose.Types.ObjectId();
|
|
const user = { _id: new mongoose.Types.ObjectId() } as UserDocument;
|
|
const findOne = jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue(user),
|
|
});
|
|
const connectionService = {
|
|
getModel: jest.fn().mockResolvedValue({ findOne }),
|
|
} as unknown as ConnectionService;
|
|
const request = {
|
|
params: { communityId: communityId.toString() },
|
|
identity: { _id: identityId } as IdentityDocument,
|
|
};
|
|
const guard = new UserResolverGuard(connectionService);
|
|
|
|
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
|
|
|
|
expect(findOne).toHaveBeenCalledWith({
|
|
communityId,
|
|
identityId,
|
|
});
|
|
expect(request.user).toBe(user);
|
|
});
|
|
|
|
it('skips lookup when there is no resolved identity', async () => {
|
|
const connectionService = {
|
|
getModel: jest.fn(),
|
|
} as unknown as ConnectionService;
|
|
const request = {
|
|
params: { communityId: new mongoose.Types.ObjectId().toString() },
|
|
};
|
|
const guard = new UserResolverGuard(connectionService);
|
|
|
|
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
|
|
|
|
expect(connectionService.getModel).not.toHaveBeenCalled();
|
|
});
|
|
});
|