@geekmidas/ testkit (英语)
现代TypeScript应用软件的型式安全测试设施和数据库工厂
概览
@geekmidas/ testkit (英语) 提供一套全面的测试工具,旨在简化TypeScript应用程序中的数据库测试. 它为创建测试数据提供了工厂模式,支持多个数据库库,并确保了整个测试过程中的类型安全.
关键特性
- 工厂模式: 用最小的锅炉板创建测试数据
- 类型安全: 完全类型Script支持,并带有自动计划推论
- 多数据库支持:与Kysely和Object.js合作
- 交易隔离: 测试隔离的内置支持
- 强化的Faker: 带有时间戳、序列和坐标的扩展假人
- AWS 模拟器: Mok Lambda 上下文和 API 网关事件
- 更好的认证: 用于认证测试的模拟适配器
安装
npm install --save-dev @geekmidas/testkit
# or
pnpm add -D @geekmidas/testkit
# or
yarn add -D @geekmidas/testkit
子路径导出
// Kysely utilities
import {
KyselyFactory,
wrapVitestKyselyTransaction,
extendWithFixtures,
} from '@geekmidas/testkit/kysely';
// Objection.js utilities
import {
ObjectionFactory,
wrapVitestObjectionTransaction,
extendWithFixtures,
} from '@geekmidas/testkit/objection';
// Other utilities
import { faker } from '@geekmidas/testkit/faker';
import { waitFor } from '@geekmidas/testkit/timer';
import { itWithDir } from '@geekmidas/testkit/os';
import { createMockContext, createMockV1Event, createMockV2Event } from '@geekmidas/testkit/aws';
import { createMockLogger } from '@geekmidas/testkit/logger';
import { memoryAdapter } from '@geekmidas/testkit/better-auth';
快速启动
带有 Kysely 的数据库工厂
import { KyselyFactory } from '@geekmidas/testkit/kysely';
import { Kysely } from 'kysely';
// Define your database schema
interface Database {
users: {
id: string;
name: string;
email: string;
createdAt: Date;
};
posts: {
id: string;
title: string;
content: string;
userId: string;
};
}
// Create builders for your tables
const builders = {
user: KyselyFactory.createBuilder<Database, 'users'>(
'users',
({ attrs, faker }) => ({
id: faker.string.uuid(),
name: faker.person.fullName(),
email: faker.internet.email(),
createdAt: new Date(),
...attrs,
})
),
post: KyselyFactory.createBuilder<Database, 'posts'>(
'posts',
({ attrs, faker }) => ({
id: faker.string.uuid(),
title: 'Test Post',
content: faker.lorem.paragraph(),
...attrs,
})
),
};
// Initialize factory
const factory = new KyselyFactory(builders, {}, db);
// Use in tests
describe('User Service', () => {
it('should create a user with posts', async () => {
const user = await factory.insert('user', {
name: 'Jane Smith',
email: '[email protected]',
});
const posts = await factory.insertMany(3, 'post', {
userId: user.id,
});
expect(posts).toHaveLength(3);
expect(posts[0].userId).toBe(user.id);
});
});
反对 js
import { ObjectionFactory } from '@geekmidas/testkit/objection';
import { Model } from 'objection';
class User extends Model {
static tableName = 'users';
id!: string;
name!: string;
email!: string;
}
const builders = {
user: ObjectionFactory.createBuilder(
User,
({ attrs, faker }) => ({
id: faker.string.uuid(),
name: faker.person.fullName(),
email: faker.internet.email(),
...attrs,
})
),
};
const factory = new ObjectionFactory(builders, {}, knex);
const user = await factory.insert('user', { name: 'Jane Doe' });
强化的Faker
测试设备提供了强化的假冒实例,并增加了通用测试数据模式的公用事业.
import { faker } from '@geekmidas/testkit/faker';
// Standard faker methods
const name = faker.person.fullName();
const email = faker.internet.email();
// Generate timestamps for database records
const { createdAt, updatedAt } = faker.timestamps();
// createdAt: Date in the past
// updatedAt: Date between createdAt and now
// Sequential numbers (useful for unique IDs)
faker.sequence(); // 1
faker.sequence(); // 2
faker.sequence('user'); // 1 (separate sequence)
faker.sequence('user'); // 2
// Reset sequences between tests
faker.resetSequence('user');
faker.resetAllSequences();
// Generate prices as numbers
const price = faker.price(); // 29.99
// Generate reverse domain identifiers
faker.identifier(); // "com.example.widget1"
faker.identifier('user'); // "org.acme.user"
// Generate coordinates within/outside a radius
const center = { lat: 40.7128, lng: -74.0060 };
faker.coordinates.within(center, 1000); // Within 1km
faker.coordinates.outside(center, 1000, 5000); // Between 1km and 5km
计时器
简单的async 等待测试工具 .
import { waitFor } from '@geekmidas/testkit/timer';
it('should process after delay', async () => {
startBackgroundProcess();
await waitFor(100); // Wait 100ms
expect(processComplete).toBe(true);
});
OS 公用事业
Vest fixture 用于自动清理的临时目录创建.
import { itWithDir } from '@geekmidas/testkit/os';
// Creates a temp directory before test, removes it after
itWithDir('should write files to temp dir', async ({ dir }) => {
const filePath = path.join(dir, 'test.txt');
await fs.writeFile(filePath, 'hello');
const content = await fs.readFile(filePath, 'utf-8');
expect(content).toBe('hello');
// Directory is automatically cleaned up after test
});
AWS 测试工具
Mock AWS Lambda背景和API Gateway事件,用于测试Lambda处理器.
import {
createMockContext,
createMockV1Event,
createMockV2Event
} from '@geekmidas/testkit/aws';
describe('Lambda Handler', () => {
it('should handle API Gateway v1 event', async () => {
const event = createMockV1Event({
httpMethod: 'POST',
path: '/users',
body: JSON.stringify({ name: 'John' }),
});
const context = createMockContext();
const result = await handler(event, context);
expect(result.statusCode).toBe(201);
});
it('should handle API Gateway v2 event', async () => {
const event = createMockV2Event({
routeKey: 'POST /users',
rawPath: '/users',
body: JSON.stringify({ name: 'John' }),
});
const context = createMockContext();
const result = await handler(event, context);
expect(result.statusCode).toBe(201);
});
});
Logger 测试工具
创建用于测试代码的模拟日志 @geekmidas/logger。 。 。 .
import { createMockLogger } from '@geekmidas/testkit/logger';
describe('Service', () => {
it('should log errors', async () => {
const logger = createMockLogger();
const service = new MyService(logger);
await service.doSomethingRisky();
expect(logger.error).toHaveBeenCalledWith(
expect.objectContaining({ error: expect.any(Error) }),
'Operation failed'
);
});
});
更好的认证测试
用于测试Better Auth的模拟适配器,没有真正的数据库.
import { memoryAdapter } from '@geekmidas/testkit/better-auth';
import { betterAuth } from 'better-auth';
describe('Authentication', () => {
const adapter = memoryAdapter({
debugLogs: false,
initialData: {
user: [{ id: '1', email: '[email protected]', name: 'Test User' }],
},
});
const auth = betterAuth({
database: adapter,
// ... other config
});
afterEach(() => {
adapter.clear(); // Reset data between tests
});
it('should create user', async () => {
await auth.api.signUp({
email: '[email protected]',
password: 'password123',
});
const data = adapter.getAllData();
expect(data.user).toHaveLength(2);
});
});
数据库迁移
TestKit包括管理测试数据库迁移的公用事业.
import { PostgresKyselyMigrator } from '@geekmidas/testkit/kysely';
const migrator = new PostgresKyselyMigrator({
database: 'test_db',
connection: {
host: 'localhost',
port: 5432,
user: 'postgres',
password: 'password',
},
migrationFolder: './migrations',
});
// In test setup
beforeAll(async () => {
const cleanup = await migrator.start();
globalThis.cleanupDb = cleanup;
});
afterAll(async () => {
await globalThis.cleanupDb?.();
});
无效交易隔离
TestKit为自动交易隔离提供Vitest特定帮助. 每个测试在测试完成后自动回滚的交易中运行.
基本用途
import { test } from 'vitest';
import { wrapVitestKyselyTransaction } from '@geekmidas/testkit/kysely';
import { db } from './database';
// Wrap Vitest's test function with transaction support
const it = wrapVitestKyselyTransaction<Database>(
test,
() => db,
async (trx) => {
// Optional: Set up test tables or seed data
await trx.schema.createTable('users').execute();
}
);
// Each test gets its own transaction
it('should create user', async ({ trx }) => {
const user = await trx
.insertInto('users')
.values({ name: 'John' })
.returningAll()
.executeTakeFirst();
expect(user.name).toBe('John');
// Transaction is automatically rolled back after test
});
以固定器延伸
使用 extendWithFixtures 在测试中添加工厂和其他固定装置:
import { test } from 'vitest';
import {
wrapVitestKyselyTransaction,
extendWithFixtures,
KyselyFactory,
} from '@geekmidas/testkit/kysely';
// Define builders
const builders = {
user: KyselyFactory.createBuilder<Database, 'users'>('users', ({ faker }) => ({
name: faker.person.fullName(),
email: faker.internet.email(),
})),
post: KyselyFactory.createBuilder<Database, 'posts'>('posts', ({ faker }) => ({
title: faker.lorem.sentence(),
content: faker.lorem.paragraphs(),
})),
};
// Create base test with transaction
const baseTest = wrapVitestKyselyTransaction<Database>(test, () => db);
// Extend with factory fixture
const it = extendWithFixtures<
Database,
{ factory: KyselyFactory<Database, typeof builders, {}> }
>(baseTest, {
factory: (trx) => new KyselyFactory(builders, {}, trx),
});
// Both trx and factory are available in tests
it('should create user with factory', async ({ trx, factory }) => {
const user = await factory.insert('user', { name: 'Jane' });
expect(user.id).toBeDefined();
expect(user.name).toBe('Jane');
// Verify in database
const found = await trx
.selectFrom('users')
.where('id', '=', user.id)
.selectAll()
.executeTakeFirst();
expect(found?.name).toBe('Jane');
});
it('should create related records', async ({ factory }) => {
const user = await factory.insert('user');
const posts = await factory.insertMany(3, 'post', { userId: user.id });
expect(posts).toHaveLength(3);
expect(posts[0].userId).toBe(user.id);
});
多个固定
您可以添加全部接收交易的多个定着:
const it = extendWithFixtures<
Database,
{
factory: KyselyFactory<Database, typeof builders, {}>;
userRepo: UserRepository;
config: { maxUsers: number };
}
>(baseTest, {
factory: (trx) => new KyselyFactory(builders, {}, trx),
userRepo: (trx) => new UserRepository(trx),
config: () => ({ maxUsers: 100 }), // Fixtures can ignore trx if not needed
});
it('should use multiple fixtures', async ({ factory, userRepo, config }) => {
const user = await factory.insert('user');
const found = await userRepo.findById(user.id);
expect(found).toBeDefined();
expect(config.maxUsers).toBe(100);
});
反对 js
import { wrapVitestObjectionTransaction, extendWithFixtures } from '@geekmidas/testkit/objection';
const baseTest = wrapVitestObjectionTransaction(test, () => knex);
const it = extendWithFixtures<{ factory: ObjectionFactory<typeof builders, {}> }>(
baseTest,
{
factory: (trx) => new ObjectionFactory(builders, {}, trx),
}
);
手动交易隔离
为了进行更多的控制,您可以手动管理交易 :
describe('User Service', () => {
let trx: Transaction<Database>;
let factory: KyselyFactory;
beforeEach(async () => {
trx = await db.transaction();
factory = new KyselyFactory(builders, seeds, trx);
});
afterEach(async () => {
await trx.rollback();
});
it('should perform operations in isolation', async () => {
const user = await factory.insert('user');
// All changes will be rolled back after the test
});
});
种子
种子是产生复杂测试情景的函数. 使用 createSeed 以定义获得的类型安全种子功能 { attrs, factory, db } 作为单个上下文对象:
用 Kysely 定义种子
import { KyselyFactory } from '@geekmidas/testkit/kysely';
// Define seeds using createSeed for type safety
const seeds = {
// Simple seed with typed attrs
adminUser: KyselyFactory.createSeed(
async ({ attrs, factory }: {
attrs: { name?: string };
factory: KyselyFactory<Database, typeof builders, {}>;
db: Kysely<Database>
}) => {
return factory.insert('user', {
name: attrs.name || 'Admin User',
role: 'admin',
});
}
),
// Complex seed creating related records
blogWithPosts: KyselyFactory.createSeed(
async ({ attrs, factory }) => {
const author = await factory.insert('user', {
name: attrs.authorName || 'Blog Author',
role: 'author',
});
const categories = await factory.insertMany(3, 'category');
const posts = await factory.insertMany(attrs.postCount || 5, 'post', (index) => ({
title: `Post ${index + 1}`,
authorId: author.id,
categoryId: categories[index % categories.length].id,
}));
return { author, categories, posts };
}
),
};
// Create factory with seeds
const factory = new KyselyFactory(builders, seeds, db);
// Use in tests - attrs are type-safe
const admin = await factory.seed('adminUser', { name: 'Super Admin' });
const blog = await factory.seed('blogWithPosts', {
authorName: 'Jane Doe',
postCount: 10
});
以反对方式定义种子。js
import { ObjectionFactory } from '@geekmidas/testkit/objection';
import type { Knex } from 'knex';
const seeds = {
userWithProfile: ObjectionFactory.createSeed(
async ({ attrs, factory, db }: {
attrs: { email?: string };
factory: ObjectionFactory<typeof builders, {}>;
db: Knex
}) => {
const user = await factory.insert('user', {
email: attrs.email || '[email protected]',
});
await factory.insert('profile', { userId: user.id });
return user;
}
),
};
const factory = new ObjectionFactory(builders, seeds, knex);
const user = await factory.seed('userWithProfile', { email: '[email protected]' });
种子上下文对象
所有种子函数都收到一个具有三个属性的单个上下文对象:
| 财产 | 说明 |
|---|---|
attrs | 配置属性传递到 factory.seed() |
factory | 创建记录的工厂实例 |
db | 数据库连接( Kysely 或 Knex 交易) |
这个图案只允许您解构您需要的 :
// Use all three
KyselyFactory.createSeed(async ({ attrs, factory, db }) => {
// Direct db access for complex queries
const existing = await db.selectFrom('users').where('role', '=', 'admin').execute();
// ...
});
// Or just what you need
KyselyFactory.createSeed(async ({ factory }) => {
return factory.insert('user');
});
API 参考
基斯利事实
class KyselyFactory<DB, Builders, Seeds> {
constructor(
builders: Builders,
seeds: Seeds,
db: Kysely<DB> | ControlledTransaction<DB>
);
// Create a type-safe builder for a specific table
static createBuilder<DB, TableName extends keyof DB & string>(
table: TableName,
defaults?: (context: {
attrs: Partial<Insertable<DB[TableName]>>;
factory: KyselyFactory;
db: Kysely<DB>;
faker: FakerFactory;
}) => Partial<Insertable<DB[TableName]>> | Promise<...>,
autoInsert?: boolean
): BuilderFunction;
// Create a type-safe seed function
static createSeed<Seed extends FactorySeed>(
seedFn: (context: { attrs: Attrs; factory: Factory; db: DB }) => Promise<Result>
): Seed;
// Insert a single record
insert<K extends keyof Builders>(
builderName: K,
attrs?: Partial<BuilderAttrs>
): Promise<BuilderResult>;
// Insert multiple records
insertMany<K extends keyof Builders>(
count: number,
builderName: K,
attrs?: Partial<BuilderAttrs> | ((idx: number, faker: FakerFactory) => Partial<BuilderAttrs>)
): Promise<BuilderResult[]>;
// Execute a seed function
seed<K extends keyof Seeds>(
seedName: K,
attrs?: ExtractSeedAttrs<Seeds[K]> // Attrs type is extracted from seed function
): Promise<SeedResult>;
}
强化的Faker
interface EnhancedFaker extends Faker {
timestamps(): { createdAt: Date; updatedAt: Date };
sequence(name?: string): number;
resetSequence(name?: string, value?: number): void;
resetAllSequences(): void;
identifier(suffix?: string): string;
price(): number;
coordinates: {
within(center: Coordinate, radiusMeters: number): Coordinate;
outside(center: Coordinate, minRadius: number, maxRadius: number): Coordinate;
};
}
AWS 模拟器
function createMockContext(): Context;
function createMockV1Event(overrides?: Partial<APIGatewayProxyEvent>): APIGatewayProxyEvent;
function createMockV2Event(overrides?: Partial<APIGatewayProxyEventV2>): APIGatewayProxyEventV2;
内存适配器( Better Auth)
function memoryAdapter(config?: {
debugLogs?: boolean;
usePlural?: boolean;
initialData?: Record<string, any[]>;
}): DatabaseAdapter & {
clear(): void;
getAllData(): Record<string, any[]>;
getStore(): Map<string, any>;
};
测试最佳做法
- 使用交易: 总是在交易中包装测试以隔离
- 创建最小数据: 只创建每个测试所需的数据
- 复杂情景使用种子: 封装种子中的复杂设置
- 利用类型安全: 让 TypeScript 捕获计划错配
- 清理资源: 总是清理数据库连接和交易
- 重置顺序: 调用
faker.resetAllSequences()内beforeEach用于可预见身份证
捐款
我们欢迎捐款! 请看我们的 贡献指南 详细情况.
许可证
这个项目根据麻省理工学院许可证颁发——见 自由主义 详细文件.