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]: 修改补充单测 #437

Merged
merged 1 commit into from
Sep 30, 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
4 changes: 3 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
"**/*.(t|j)s",
"!**/*.module.ts",
"!**/upgrade.*.ts"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node",
Expand Down
30 changes: 0 additions & 30 deletions server/src/models/__test/base.entity.spec.ts

This file was deleted.

57 changes: 57 additions & 0 deletions server/src/models/__test/surveyMeta.entity.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { SurveyMeta } from '../surveyMeta.entity';
import { RECORD_STATUS, RECORD_SUB_STATUS } from 'src/enums';

// 模拟日期
const mockDateNow = Date.now();

describe('SurveyMeta Entity', () => {
let surveyMeta: SurveyMeta;

// 在每个测试之前,初始化 SurveyMeta 实例
beforeEach(() => {
surveyMeta = new SurveyMeta();
// 模拟 Date.now() 返回固定的时间
jest.spyOn(Date, 'now').mockReturnValue(mockDateNow);
});

afterEach(() => {
jest.restoreAllMocks(); // 每次测试后还原所有 mock
});

it('should set default curStatus and subStatus on insert when they are not provided', () => {
surveyMeta.initDefaultInfo();

// 验证 curStatus 是否被初始化为默认值
expect(surveyMeta.curStatus).toEqual({
status: RECORD_STATUS.NEW,
date: mockDateNow,
});

// 验证 statusList 是否包含 curStatus
expect(surveyMeta.statusList).toEqual([
{
status: RECORD_STATUS.NEW,
date: mockDateNow,
},
]);

// 验证 subStatus 是否被初始化为默认值
expect(surveyMeta.subStatus).toEqual({
status: RECORD_SUB_STATUS.DEFAULT,
date: mockDateNow,
});
});

it('should initialize statusList if curStatus is provided but statusList is empty', () => {
surveyMeta.curStatus = null;

surveyMeta.initDefaultInfo();

expect(surveyMeta.statusList).toEqual([
{
status: RECORD_STATUS.NEW,
date: expect.any(Number),
},
]);
});
});
12 changes: 6 additions & 6 deletions server/src/modules/auth/__test/user.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ describe('UserService', () => {
it('should return a list of users by username', async () => {
const username = 'test';
const userList = [
{ _id: new ObjectId(), username: 'testUser1', createDate: new Date() },
{ _id: new ObjectId(), username: 'testUser2', createDate: new Date() },
{ _id: new ObjectId(), username: 'testUser1', createdAt: new Date() },
{ _id: new ObjectId(), username: 'testUser2', createdAt: new Date() },
];

jest
Expand All @@ -226,7 +226,7 @@ describe('UserService', () => {
},
skip: 0,
take: 10,
select: ['_id', 'username', 'createDate'],
select: ['_id', 'username', 'createdAt'],
});
expect(result).toEqual(userList);
});
Expand All @@ -237,12 +237,12 @@ describe('UserService', () => {
{
_id: new ObjectId(idList[0]),
username: 'testUser1',
createDate: new Date(),
createdAt: new Date(),
},
{
_id: new ObjectId(idList[1]),
username: 'testUser2',
createDate: new Date(),
createdAt: new Date(),
},
];

Expand All @@ -258,7 +258,7 @@ describe('UserService', () => {
$in: idList.map((id) => new ObjectId(id)),
},
},
select: ['_id', 'username', 'createDate'],
select: ['_id', 'username', 'createdAt'],
});
expect(result).toEqual(userList);
});
Expand Down
18 changes: 5 additions & 13 deletions server/src/modules/message/__test/messagePushingTask.dto.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
MESSAGE_PUSHING_TYPE,
MESSAGE_PUSHING_HOOK,
} from 'src/enums/messagePushing';
import { RECORD_STATUS } from 'src/enums';

describe('MessagePushingTaskDto', () => {
let dto: MessagePushingTaskDto;
Expand All @@ -34,9 +33,9 @@ describe('MessagePushingTaskDto', () => {
});

it('should have a type', () => {
dto.type = MESSAGE_PUSHING_TYPE.HTTP; // Set your desired type here
dto.type = MESSAGE_PUSHING_TYPE.HTTP;
expect(dto.type).toBeDefined();
expect(dto.type).toEqual(MESSAGE_PUSHING_TYPE.HTTP); // Adjust based on your enum
expect(dto.type).toEqual(MESSAGE_PUSHING_TYPE.HTTP);
});

it('should have a push address', () => {
Expand All @@ -46,13 +45,13 @@ describe('MessagePushingTaskDto', () => {
});

it('should have a trigger hook', () => {
dto.triggerHook = MESSAGE_PUSHING_HOOK.RESPONSE_INSERTED; // Set your desired hook here
dto.triggerHook = MESSAGE_PUSHING_HOOK.RESPONSE_INSERTED;
expect(dto.triggerHook).toBeDefined();
expect(dto.triggerHook).toEqual(MESSAGE_PUSHING_HOOK.RESPONSE_INSERTED); // Adjust based on your enum
expect(dto.triggerHook).toEqual(MESSAGE_PUSHING_HOOK.RESPONSE_INSERTED);
});

it('should have an array of surveys', () => {
dto.surveys = ['survey1', 'survey2']; // Set your desired surveys here
dto.surveys = ['survey1', 'survey2'];
expect(dto.surveys).toBeDefined();
expect(dto.surveys).toEqual(['survey1', 'survey2']);
});
Expand All @@ -62,13 +61,6 @@ describe('MessagePushingTaskDto', () => {
expect(dto.owner).toBeDefined();
expect(dto.owner).toBe('test_owner');
});

it('should have current status', () => {
dto.curStatus = { status: RECORD_STATUS.NEW, date: Date.now() };
expect(dto.curStatus).toBeDefined();
expect(dto.curStatus.status).toEqual(RECORD_STATUS.NEW);
expect(dto.curStatus.date).toBeDefined();
});
});

describe('CodeDto', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ describe('MessagePushingTaskService', () => {
expect(result).toEqual(tasks);
expect(repository.find).toHaveBeenCalledWith({
where: {
isDeleted: {
$ne: true,
},
ownerId: mockOwnerId,
surveys: { $all: [surveyId] },
triggerHook: hook,
Expand Down Expand Up @@ -144,9 +147,19 @@ describe('MessagePushingTaskService', () => {
where: {
ownerId: mockOwnerId,
_id: new ObjectId(taskId),
isDeleted: {
$ne: true,
},
},
});
});
it('should throw an error when message pushing task is not found', async () => {
const taskId = '65afc62904d5db18534c0f78';
jest.spyOn(repository, 'findOne').mockResolvedValue(null); // 模拟未找到任务
const mockOwnerId = '66028642292c50f8b71a9eee';

await expect(service.findOne({ id: taskId, ownerId: mockOwnerId }));
});
});

describe('update', () => {
Expand Down Expand Up @@ -183,6 +196,20 @@ describe('MessagePushingTaskService', () => {
});
expect(repository.save).toHaveBeenCalledWith(updatedTask);
});
it('should throw an error if the task to be updated is not found', async () => {
const taskId = '65afc62904d5db18534c0f78';
const updateDto: UpdateMessagePushingTaskDto = { name: 'Updated Task' };
jest.spyOn(repository, 'findOne').mockResolvedValue(null); // 模拟任务未找到
const mockOwnerId = '66028642292c50f8b71a9eee';

await expect(
service.update({
ownerId: mockOwnerId,
id: taskId,
updateData: updateDto,
}),
).rejects.toThrow(`Message pushing task with id ${taskId} not found`);
});
});

describe('remove', () => {
Expand All @@ -204,16 +231,40 @@ describe('MessagePushingTaskService', () => {
expect(result).toEqual(updateResult);
expect(repository.updateOne).toHaveBeenCalledWith(
{
ownerId: mockOperatorId,
_id: new ObjectId(taskId),
},
{
$set: {
isDeleted: true,
operatorId: mockOperatorId,
operator: mockOperator,
deletedAt: expect.any(Date),
},
},
);
});
it('should throw an error if the task to be removed is not found', async () => {
const taskId = '65afc62904d5db18534c0f78';
jest
.spyOn(repository, 'updateOne')
.mockResolvedValue({ modifiedCount: 0 }); // 模拟删除失败
const mockOperatorId = '66028642292c50f8b71a9eee';
const mockOperator = 'mockOperator';

const result = await service.remove({
id: taskId,
operatorId: mockOperatorId,
operator: mockOperator,
});

expect(result.modifiedCount).toBe(0);
expect(repository.updateOne).toHaveBeenCalledWith(
{
_id: new ObjectId(taskId),
},
expect.any(Object),
);
});
});

describe('surveyAuthorizeTask', () => {
Expand Down Expand Up @@ -243,7 +294,34 @@ describe('MessagePushingTaskService', () => {
$push: {
surveys: surveyId,
},
$set: {
updatedAt: expect.any(Date),
},
},
);
});
it('should not add the surveyId if it already exists in the task', async () => {
const taskId = '65afc62904d5db18534c0f78';
const surveyId = '65af380475b64545e5277dd9';
const mockOwnerId = '66028642292c50f8b71a9eee';

jest
.spyOn(repository, 'updateOne')
.mockResolvedValue({ modifiedCount: 0 }); // 模拟重复添加
const result = await service.surveyAuthorizeTask({
taskId,
surveyId,
ownerId: mockOwnerId,
});

expect(result.modifiedCount).toBe(0);
expect(repository.updateOne).toHaveBeenCalledWith(
{
_id: new ObjectId(taskId),
surveys: { $nin: [surveyId] }, // 确保只有不包含时才插入
ownerId: mockOwnerId,
},
expect.any(Object),
);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,4 @@ describe('UpdateMessagePushingTaskDto', () => {
dto.surveys = null;
expect(dto.surveys).toBeNull();
});

it('should have a nullable curStatus', () => {
dto.curStatus = null;
expect(dto.curStatus).toBeNull();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,14 @@ export class MessagePushingTaskService {
});
}

async findOne({
findOne({
id,
ownerId,
}: {
id: string;
ownerId: string;
}): Promise<MessagePushingTask> {
return await this.messagePushingTaskRepository.findOne({
return this.messagePushingTaskRepository.findOne({
where: {
ownerId,
_id: new ObjectId(id),
Expand Down
Loading