Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature]:我的空间新增分组管理 #439

Merged
merged 18 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { SurveyHistory } from './models/surveyHistory.entity';
import { ResponseSchema } from './models/responseSchema.entity';
import { Counter } from './models/counter.entity';
import { SurveyResponse } from './models/surveyResponse.entity';
import { SurveyGroup } from './models/surveyGroup.entity';
import { ClientEncrypt } from './models/clientEncrypt.entity';
import { Word } from './models/word.entity';
import { MessagePushingTask } from './models/messagePushingTask.entity';
Expand Down Expand Up @@ -78,6 +79,7 @@ import { Logger } from './logger';
SurveyConf,
SurveyHistory,
SurveyResponse,
SurveyGroup,
Counter,
ResponseSchema,
ClientEncrypt,
Expand Down
11 changes: 11 additions & 0 deletions server/src/models/surveyGroup.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Entity, Column } from 'typeorm';
import { BaseEntity } from './base.entity';

@Entity({ name: 'surveyGroup' })
export class SurveyGroup extends BaseEntity {
@Column()
ownerId: string;

@Column()
name: string;
}
3 changes: 3 additions & 0 deletions server/src/models/surveyMeta.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ export class SurveyMeta extends BaseEntity {
@Column()
workspaceId: string;

@Column()
groupId: string;

@Column()
curStatus: {
status: RECORD_STATUS;
Expand Down
132 changes: 132 additions & 0 deletions server/src/modules/survey/__test/surveyGroup.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SurveyGroupController } from '../controllers/surveyGroup.controller';
import { SurveyGroupService } from '../services/surveyGroup.service';
import { SurveyMetaService } from '../services/surveyMeta.service';
import { HttpException } from 'src/exceptions/httpException';
import { ObjectId } from 'mongodb';
import { Logger } from 'src/logger';

jest.mock('src/guards/authentication.guard');

describe('SurveyGroupController', () => {
let controller: SurveyGroupController;
let service: SurveyGroupService;

const mockService = {
create: jest.fn(),
findAll: jest.fn(),
update: jest.fn(),
remove: jest.fn(),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [SurveyGroupController],
providers: [
{
provide: SurveyMetaService,
useValue: {
countSurveyMetaByGroupId: jest.fn().mockResolvedValue(0),
},
},
{
provide: SurveyGroupService,
useValue: mockService,
},
{
provide: Logger,
useValue: {
error: jest.fn(),
info: jest.fn(),
},
},
],
}).compile();

controller = module.get<SurveyGroupController>(SurveyGroupController);
service = module.get<SurveyGroupService>(SurveyGroupService);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});

describe('create', () => {
it('should create a survey group', async () => {
const result = {
_id: new ObjectId(),
name: 'Test Group',
ownerId: '123',
createdAt: new Date(),
updatedAt: new Date(),
}; // 确保这里返回的对象结构符合预期
jest.spyOn(service, 'create').mockResolvedValue(result);

// 创建模拟的请求对象
const req = {
user: {
_id: '123', // 模拟的用户ID
},
};

expect(await controller.create({ name: 'Test Group' }, req)).toEqual({
code: 200,
data: {
id: result._id,
},
});
expect(service.create).toHaveBeenCalledWith({
name: 'Test Group',
ownerId: req.user._id.toString(), // 这里用模拟的 req.user._id
});
});
});

describe('findAll', () => {
it('should return a list of survey groups', async () => {
const result = { total: 0, notTotal: 0, list: [], allList: [] };
jest.spyOn(service, 'findAll').mockResolvedValue(result);
const mockReq = { user: { _id: new ObjectId() } };
const mockQue = { curPage: 1, pageSize: 10, name: '' };
const userId = mockReq.user._id.toString();
expect(await controller.findAll(mockReq, mockQue)).toEqual({
code: 200,
data: result,
});
expect(service.findAll).toHaveBeenCalledWith(userId, '', 0, 10);
});
});

describe('update', () => {
it('should update a survey group', async () => {
const updatedFields = { name: 'xxx' };
const updatedResult = { raw: 'xxx', generatedMaps: [] };
const id = '1';
jest.spyOn(service, 'update').mockResolvedValue(updatedResult);

expect(await controller.updateOne(id, updatedFields)).toEqual({
code: 200,
ret: updatedResult,
});
expect(service.update).toHaveBeenCalledWith(id, updatedFields);
});

it('should throw error on invalid parameter', async () => {
const id = '1';
const invalidFields: any = {};
await expect(controller.updateOne(id, invalidFields)).rejects.toThrow(
HttpException,
);
});
});

describe('remove', () => {
it('should remove a survey group', async () => {
const id = '1';
jest.spyOn(service, 'remove').mockResolvedValue(undefined);

expect(await controller.remove(id)).toEqual({ code: 200 });
expect(service.remove).toHaveBeenCalledWith(id);
});
});
});
102 changes: 102 additions & 0 deletions server/src/modules/survey/__test/surveyGroup.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SurveyGroupService } from '../services/surveyGroup.service';
import { SurveyGroup } from 'src/models/surveyGroup.entity';
import { SurveyMeta } from 'src/models/surveyMeta.entity';
import { getRepositoryToken } from '@nestjs/typeorm';

describe('SurveyGroupService', () => {
let service: SurveyGroupService;

const mockSurveyGroupRepository = {
create: jest.fn(),
save: jest.fn(),
findAndCount: jest.fn(),
find: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
};

const mockSurveyMetaRepository = {
updateMany: jest.fn(),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
SurveyGroupService,
{
provide: getRepositoryToken(SurveyGroup),
useValue: mockSurveyGroupRepository,
},
{
provide: getRepositoryToken(SurveyMeta),
useValue: mockSurveyMetaRepository,
},
],
}).compile();

service = module.get<SurveyGroupService>(SurveyGroupService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});

describe('create', () => {
it('should create a survey group', async () => {
const createParams = { name: 'Test Group', ownerId: '123' };
const mockSavedGroup = { ...createParams, id: '1' };

mockSurveyGroupRepository.create.mockReturnValue(mockSavedGroup);
mockSurveyGroupRepository.save.mockResolvedValue(mockSavedGroup);

expect(await service.create(createParams)).toEqual(mockSavedGroup);
expect(mockSurveyGroupRepository.create).toHaveBeenCalledWith(
createParams,
);
expect(mockSurveyGroupRepository.save).toHaveBeenCalledWith(
mockSavedGroup,
);
});
});

describe('findAll', () => {
it('should return survey groups', async () => {
const list = [{ id: '1', name: 'Test Group', ownerId: '123' }];
const total = list.length;

mockSurveyGroupRepository.findAndCount.mockResolvedValue([list, total]);
mockSurveyGroupRepository.find.mockResolvedValue(list);

const result = await service.findAll('123', '', 0, 10);
expect(result).toEqual({ total, list, allList: list });
expect(mockSurveyGroupRepository.findAndCount).toHaveBeenCalled();
expect(mockSurveyGroupRepository.find).toHaveBeenCalled();
});
});

describe('update', () => {
it('should update a survey group', async () => {
const id = '1';
const updatedFields = { name: 'Updated Test Group' };

await service.update(id, updatedFields);
expect(mockSurveyGroupRepository.update).toHaveBeenCalledWith(id, {
...updatedFields,
updatedAt: expect.any(Date),
});
});
});

describe('remove', () => {
it('should remove a survey group', async () => {
const id = '1';
await service.remove(id);
expect(mockSurveyMetaRepository.updateMany).toHaveBeenCalledWith(
{ groupId: id },
{ $set: { groupId: null } },
);
expect(mockSurveyGroupRepository.delete).toHaveBeenCalledWith(id);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ describe('SurveyMetaController', () => {
survey: {
title: reqBody.title,
remark: reqBody.remark,
groupId: null,
},
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ describe('SurveyMetaService', () => {
createMethod: params.createMethod,
createFrom: params.createFrom,
workspaceId: params.workspaceId,
groupId: null,
});
expect(surveyRepository.save).toHaveBeenCalledWith(newSurvey);
expect(result).toEqual(newSurvey);
Expand Down
3 changes: 2 additions & 1 deletion server/src/modules/survey/controllers/survey.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class SurveyController {
throw new HttpException('参数错误', EXCEPTION_CODE.PARAMETER_ERROR);
}

const { title, remark, createMethod, createFrom } = value;
const { title, remark, createMethod, createFrom, groupId } = value;

let surveyType = '',
workspaceId = null;
Expand All @@ -100,6 +100,7 @@ export class SurveyController {
createMethod,
createFrom,
workspaceId,
groupId,
});
await this.surveyConfService.createSurveyConf({
surveyId: surveyMeta._id.toString(),
Expand Down
Loading
Loading