mirror of
https://github.com/labring/FastGPT.git
synced 2025-07-28 17:29:44 +00:00
chore: Jest Testing structure (#2707)
* deps: add jest deps * chore: mock * feat: use mocinggoose * feat: jest * chore: remove babel.config.js
This commit is contained in:
76
projects/app/src/pages/api/__mocks__/base.ts
Normal file
76
projects/app/src/pages/api/__mocks__/base.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { MongoMemoryServer } from 'mongodb-memory-server';
|
||||
import mongoose from 'mongoose';
|
||||
import { MockParseHeaderCert } from '@/test/utils';
|
||||
import { initMockData } from './db/init';
|
||||
|
||||
jest.mock('nanoid', () => {
|
||||
return {
|
||||
nanoid: () => {}
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('@fastgpt/global/common/string/tools', () => {
|
||||
return {
|
||||
hashStr(str: string) {
|
||||
return str;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('@fastgpt/service/common/system/log', jest.fn());
|
||||
|
||||
jest.mock('@fastgpt/service/support/permission/controller', () => {
|
||||
return {
|
||||
parseHeaderCert: MockParseHeaderCert,
|
||||
getResourcePermission: jest.requireActual('@fastgpt/service/support/permission/controller')
|
||||
.getResourcePermission,
|
||||
getResourceAllClbs: jest.requireActual('@fastgpt/service/support/permission/controller')
|
||||
.getResourceAllClbs
|
||||
};
|
||||
});
|
||||
|
||||
const parse = jest.createMockFromModule('@fastgpt/service/support/permission/controller') as any;
|
||||
parse.parseHeaderCert = MockParseHeaderCert;
|
||||
|
||||
jest.mock('@/service/middleware/entry', () => {
|
||||
return {
|
||||
NextAPI: (...args: any) => {
|
||||
return async function api(req: any, res: any) {
|
||||
try {
|
||||
let response = null;
|
||||
for (const handler of args) {
|
||||
response = await handler(req, res);
|
||||
}
|
||||
return {
|
||||
code: 200,
|
||||
data: response
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
code: 500,
|
||||
error
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!global.mongod || !global.mongodb) {
|
||||
const mongod = await MongoMemoryServer.create();
|
||||
global.mongod = mongod;
|
||||
global.mongodb = mongoose;
|
||||
await global.mongodb.connect(mongod.getUri());
|
||||
await initMockData();
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (global.mongodb) {
|
||||
await global.mongodb.disconnect();
|
||||
}
|
||||
if (global.mongod) {
|
||||
await global.mongod.stop();
|
||||
}
|
||||
});
|
48
projects/app/src/pages/api/__mocks__/db/init.ts
Normal file
48
projects/app/src/pages/api/__mocks__/db/init.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { TeamMemberRoleEnum } from '@fastgpt/global/support/user/team/constant';
|
||||
import { MongoApp } from '@fastgpt/service/core/app/schema';
|
||||
import { MongoUser } from '@fastgpt/service/support/user/schema';
|
||||
import { MongoTeamMember } from '@fastgpt/service/support/user/team/teamMemberSchema';
|
||||
import { MongoTeam } from '@fastgpt/service/support/user/team/teamSchema';
|
||||
|
||||
export const root = {
|
||||
uid: '',
|
||||
tmbId: '',
|
||||
teamId: '',
|
||||
isRoot: true,
|
||||
appId: ''
|
||||
};
|
||||
|
||||
export const initMockData = async () => {
|
||||
// init root user
|
||||
const rootUser = await MongoUser.create({
|
||||
username: 'root',
|
||||
password: '123456'
|
||||
});
|
||||
|
||||
const rootTeam = await MongoTeam.create({
|
||||
name: 'root-default-team',
|
||||
ownerId: rootUser._id
|
||||
});
|
||||
|
||||
const rootTeamMember = await MongoTeamMember.create({
|
||||
teamId: rootTeam._id,
|
||||
userId: rootUser._id,
|
||||
name: 'root-default-team-member',
|
||||
status: 'active',
|
||||
role: TeamMemberRoleEnum.owner
|
||||
});
|
||||
|
||||
const rootApp = await MongoApp.create({
|
||||
name: 'root-default-app',
|
||||
teamId: rootTeam._id,
|
||||
tmbId: rootTeam._id,
|
||||
type: 'advanced'
|
||||
});
|
||||
|
||||
root.uid = rootUser._id;
|
||||
root.tmbId = rootTeamMember._id;
|
||||
root.teamId = rootTeam._id;
|
||||
root.appId = rootApp._id;
|
||||
|
||||
await Promise.all([rootUser.save(), rootTeam.save(), rootTeamMember.save(), rootApp.save()]);
|
||||
};
|
4
projects/app/src/pages/api/__mocks__/type.d.ts
vendored
Normal file
4
projects/app/src/pages/api/__mocks__/type.d.ts
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
import { MongoMemoryServer } from 'mongodb-memory-server';
|
||||
declare global {
|
||||
var mongod: MongoMemoryServer | undefined;
|
||||
}
|
67
projects/app/src/pages/api/support/outLink/list.test.ts
Normal file
67
projects/app/src/pages/api/support/outLink/list.test.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import '../../__mocks__/base';
|
||||
import { root } from '../../__mocks__/db/init';
|
||||
import { getTestRequest } from '@/test/utils';
|
||||
import type { OutLinkListQuery } from './list';
|
||||
import { AppErrEnum } from '@fastgpt/global/common/error/code/app';
|
||||
import handler from './list';
|
||||
import { MongoOutLink } from '@fastgpt/service/support/outLink/schema';
|
||||
|
||||
beforeAll(async () => {
|
||||
await MongoOutLink.create({
|
||||
shareId: 'aaa',
|
||||
appId: root.appId,
|
||||
tmbId: root.tmbId,
|
||||
teamId: root.teamId,
|
||||
type: 'share',
|
||||
name: 'aaa'
|
||||
});
|
||||
await MongoOutLink.create({
|
||||
shareId: 'bbb',
|
||||
appId: root.appId,
|
||||
tmbId: root.tmbId,
|
||||
teamId: root.teamId,
|
||||
type: 'share',
|
||||
name: 'bbb'
|
||||
});
|
||||
});
|
||||
|
||||
test('Should return a list of outLink', async () => {
|
||||
const res = (await handler(
|
||||
...getTestRequest<OutLinkListQuery>({
|
||||
query: {
|
||||
appId: root.appId,
|
||||
type: 'share'
|
||||
},
|
||||
user: root
|
||||
})
|
||||
)) as any;
|
||||
|
||||
expect(res.code).toBe(200);
|
||||
expect(res.data.length).toBe(2);
|
||||
});
|
||||
|
||||
test('appId is required', async () => {
|
||||
const res = (await handler(
|
||||
...getTestRequest<OutLinkListQuery>({
|
||||
query: {
|
||||
type: 'share'
|
||||
},
|
||||
user: root
|
||||
})
|
||||
)) as any;
|
||||
expect(res.code).toBe(500);
|
||||
expect(res.error).toBe(AppErrEnum.unExist);
|
||||
});
|
||||
|
||||
test('if type is not provided, return nothing', async () => {
|
||||
const res = (await handler(
|
||||
...getTestRequest<OutLinkListQuery>({
|
||||
query: {
|
||||
appId: root.appId
|
||||
},
|
||||
user: root
|
||||
})
|
||||
)) as any;
|
||||
expect(res.code).toBe(200);
|
||||
expect(res.data.length).toBe(0);
|
||||
});
|
@@ -4,6 +4,7 @@ import { ManagePermissionVal } from '@fastgpt/global/support/permission/constant
|
||||
import type { ApiRequestProps } from '@fastgpt/service/type/next';
|
||||
import { NextAPI } from '@/service/middleware/entry';
|
||||
import { OutLinkSchema } from '@fastgpt/global/support/outLink/type';
|
||||
import { PublishChannelEnum } from '@fastgpt/global/support/outLink/constant';
|
||||
|
||||
export const ApiMetadata = {
|
||||
name: '获取应用内所有 Outlink',
|
||||
@@ -11,19 +12,18 @@ export const ApiMetadata = {
|
||||
version: '0.1.0'
|
||||
};
|
||||
|
||||
// Outlink
|
||||
export type OutLinkListQuery = {
|
||||
appId: string; // 应用 ID
|
||||
type: string; // 类型
|
||||
type: `${PublishChannelEnum}`;
|
||||
};
|
||||
|
||||
export type OutLinkListBody = {};
|
||||
|
||||
// 响应: 应用内全部 Outlink
|
||||
// 应用内全部 Outlink 列表
|
||||
export type OutLinkListResponse = OutLinkSchema[];
|
||||
|
||||
// 查询应用内全部 Outlink
|
||||
async function handler(
|
||||
// 查询应用的所有 OutLink
|
||||
export async function handler(
|
||||
req: ApiRequestProps<OutLinkListBody, OutLinkListQuery>
|
||||
): Promise<OutLinkListResponse> {
|
||||
const { appId, type } = req.query;
|
||||
@@ -43,4 +43,5 @@ async function handler(
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
export default NextAPI(handler);
|
||||
|
48
projects/app/src/pages/api/support/outLink/update.test.ts
Normal file
48
projects/app/src/pages/api/support/outLink/update.test.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { getTestRequest } from '@/test/utils';
|
||||
import '../../__mocks__/base';
|
||||
import handler, { OutLinkUpdateBody, OutLinkUpdateQuery } from './update';
|
||||
import { root } from '../../__mocks__/db/init';
|
||||
import { MongoOutLink } from '@fastgpt/service/support/outLink/schema';
|
||||
import { CommonErrEnum } from '@fastgpt/global/common/error/code/common';
|
||||
|
||||
test('Update Outlink', async () => {
|
||||
const outlink = await MongoOutLink.create({
|
||||
shareId: 'aaa',
|
||||
appId: root.appId,
|
||||
tmbId: root.tmbId,
|
||||
teamId: root.teamId,
|
||||
type: 'share',
|
||||
name: 'aaa'
|
||||
});
|
||||
|
||||
await outlink.save();
|
||||
|
||||
const res = (await handler(
|
||||
...getTestRequest<OutLinkUpdateQuery, OutLinkUpdateBody>({
|
||||
body: {
|
||||
_id: outlink._id,
|
||||
name: 'changed'
|
||||
},
|
||||
user: root
|
||||
})
|
||||
)) as any;
|
||||
|
||||
expect(res.code).toBe(200);
|
||||
|
||||
const link = await MongoOutLink.findById(outlink._id).lean();
|
||||
expect(link?.name).toBe('changed');
|
||||
});
|
||||
|
||||
test('Did not post _id', async () => {
|
||||
const res = (await handler(
|
||||
...getTestRequest<OutLinkUpdateQuery, OutLinkUpdateBody>({
|
||||
body: {
|
||||
name: 'changed'
|
||||
},
|
||||
user: root
|
||||
})
|
||||
)) as any;
|
||||
|
||||
expect(res.code).toBe(500);
|
||||
expect(res.error).toBe(CommonErrEnum.missingParams);
|
||||
});
|
@@ -7,7 +7,18 @@ import { NextAPI } from '@/service/middleware/entry';
|
||||
import { CommonErrEnum } from '@fastgpt/global/common/error/code/common';
|
||||
|
||||
export type OutLinkUpdateQuery = {};
|
||||
export type OutLinkUpdateBody = OutLinkEditType & {};
|
||||
|
||||
// {
|
||||
// _id?: string; // Outlink 的 ID
|
||||
// name: string; // Outlink 的名称
|
||||
// responseDetail?: boolean; // 是否开启详细回复
|
||||
// immediateResponse?: string; // 立即回复的内容
|
||||
// defaultResponse?: string; // 默认回复的内容
|
||||
// limit?: OutLinkSchema<T>['limit']; // 限制
|
||||
// app?: T; // 平台的配置
|
||||
// }
|
||||
export type OutLinkUpdateBody = OutLinkEditType;
|
||||
|
||||
export type OutLinkUpdateResponse = {};
|
||||
|
||||
async function handler(
|
||||
|
94
projects/app/src/test/utils.ts
Normal file
94
projects/app/src/test/utils.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { ERROR_ENUM } from '@fastgpt/global/common/error/errorCode';
|
||||
|
||||
export type TestTokenType = {
|
||||
userId: string;
|
||||
teamId: string;
|
||||
tmbId: string;
|
||||
isRoot: boolean;
|
||||
};
|
||||
|
||||
export type TestRequest = {
|
||||
headers: {
|
||||
cookie?: {
|
||||
token?: TestTokenType;
|
||||
};
|
||||
authorization?: string; // testkey
|
||||
rootkey?: string; // rootkey
|
||||
};
|
||||
query: {
|
||||
[key: string]: string;
|
||||
};
|
||||
body: {
|
||||
[key: string]: string;
|
||||
};
|
||||
};
|
||||
|
||||
export function getTestRequest<Q = any, B = any>({
|
||||
query = {},
|
||||
body = {},
|
||||
authToken = true,
|
||||
// authRoot = false,
|
||||
// authApiKey = false,
|
||||
user
|
||||
}: {
|
||||
body?: Partial<B>;
|
||||
query?: Partial<Q>;
|
||||
authToken?: boolean;
|
||||
authRoot?: boolean;
|
||||
authApiKey?: boolean;
|
||||
user?: {
|
||||
uid: string;
|
||||
tmbId: string;
|
||||
teamId: string;
|
||||
isRoot: boolean;
|
||||
};
|
||||
}): [any, any] {
|
||||
const headers: TestRequest['headers'] = {};
|
||||
if (authToken) {
|
||||
headers.cookie = {
|
||||
token: {
|
||||
userId: String(user?.uid || ''),
|
||||
teamId: String(user?.teamId || ''),
|
||||
tmbId: String(user?.tmbId || ''),
|
||||
isRoot: user?.isRoot || false
|
||||
}
|
||||
};
|
||||
}
|
||||
return [
|
||||
{
|
||||
headers,
|
||||
query,
|
||||
body
|
||||
},
|
||||
{}
|
||||
];
|
||||
}
|
||||
|
||||
export const MockParseHeaderCert = async ({
|
||||
req,
|
||||
authToken = true,
|
||||
authRoot = false,
|
||||
authApiKey = false
|
||||
}: {
|
||||
req: TestRequest;
|
||||
authToken?: boolean;
|
||||
authRoot?: boolean;
|
||||
authApiKey?: boolean;
|
||||
}): Promise<TestTokenType> => {
|
||||
if (authToken) {
|
||||
const token = req.headers?.cookie?.token;
|
||||
if (!token) {
|
||||
return Promise.reject(ERROR_ENUM.unAuthorization);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
// if (authRoot) {
|
||||
// // TODO: unfinished
|
||||
// return req.headers.rootkey;
|
||||
// }
|
||||
// if (authApiKey) {
|
||||
// // TODO: unfinished
|
||||
// return req.headers.authorization;
|
||||
// }
|
||||
return {} as any;
|
||||
};
|
Reference in New Issue
Block a user