From a96bf093160d0b50dd22dfc20445eb00b2361057 Mon Sep 17 00:00:00 2001 From: chenos Date: Thu, 10 Dec 2020 10:12:27 +0800 Subject: [PATCH] test: add hook test cases --- packages/database/src/__tests__/hooks.test.ts | 84 +++++++++++++++++++ packages/database/src/__tests__/index.ts | 3 + 2 files changed, 87 insertions(+) create mode 100644 packages/database/src/__tests__/hooks.test.ts diff --git a/packages/database/src/__tests__/hooks.test.ts b/packages/database/src/__tests__/hooks.test.ts new file mode 100644 index 000000000..7e913569f --- /dev/null +++ b/packages/database/src/__tests__/hooks.test.ts @@ -0,0 +1,84 @@ +import { getDatabase } from './'; +import Database from '../database'; +import Table from '../table'; +import Model from '../model'; +import { FieldContext, Integer, registerField } from '../fields'; + +class TestHookField extends Integer { + constructor(options: any, context: FieldContext) { + super(options, context); + const Model = context.sourceTable.getModel(); + Model.addHook('beforeCreate', (model) => { + model.set('name', 'beforeCreate123'); + console.log('beforeCreate123'); + }); + Model.addHook('afterCreate', (model) => { + model.set('title', 'afterCreate123'); + console.log('afterCreate123'); + }); + } +} + +registerField('testHook', TestHookField); + +let db: Database; + +beforeEach(async () => { + db = getDatabase(); +}); + +afterEach(async () => { + await db.close(); +}); + +describe('hooks', () => { + it('add hook in custom field', async () => { + db.table({ + name: 'testHook', + fields: [ + { + type: 'string', + name: 'name', + }, + { + type: 'testHook', + name: 'testHook', + }, + { + type: 'string', + name: 'title', + }, + ], + }); + await db.sync(); + const TestHook = db.getModel('testHook'); + const test = await TestHook.create({}); + expect(test.get('name')).toBe('beforeCreate123'); + }); + + it('add hook in custom field', async () => { + const table = db.table({ + name: 'test2', + fields: [ + { + type: 'string', + name: 'name', + }, + ], + }); + // 通过 table 新增 + table.addField({ + type: 'testHook', + name: 'testHook', + }); + table.addField({ + type: 'string', + name: 'title', + }); + await table.sync(); + const Test2 = db.getModel('test2'); + const test = await Test2.create({}); + expect(test.get('name')).toBe('beforeCreate123'); + expect(test.get('title')).toBe('afterCreate123'); + }); +}); diff --git a/packages/database/src/__tests__/index.ts b/packages/database/src/__tests__/index.ts index 448c326fd..d9b9b4842 100644 --- a/packages/database/src/__tests__/index.ts +++ b/packages/database/src/__tests__/index.ts @@ -30,6 +30,9 @@ const config = { export function getDatabase() { return new Database({ ...config, + sync: { + force: true, + }, hooks: { beforeDefine(columns, model) { model.tableName = `${getTestKey()}_${model.tableName || model.name.plural}`;