const Entity = require('../src/models/Entity'); const Content = require('../src/models/Content'); const EntityContentJoin = require('../src/models/EntityContentJoin'); const { getDb, closeDb } = require('../src/config/database'); const { migrate } = require('../src/database/migrate'); beforeAll(() => { migrate(); }); afterAll(() => { closeDb(); }); describe('EntityContentJoin Model', () => { let entity1Id, content1Id, joinId; beforeAll(() => { // 创建测试实体 const entity1 = Entity.create({ name: '测试实体', definition: '用于测试关联的实体' }); entity1Id = entity1.entity_id; // 创建测试内容 const content1 = Content.create({ title: '测试内容', body: '用于测试关联的内容', content_type: 'article', publish_status: 'draft' }); content1Id = content1.content_id; }); test('应该创建关联', () => { const join = EntityContentJoin.create({ entity_id: entity1Id, content_id: content1Id, join_note: '测试关联备注' }); expect(join).toBeDefined(); expect(join.join_id).toBeDefined(); expect(join.entity_id).toBe(entity1Id); expect(join.content_id).toBe(content1Id); expect(join.join_note).toBe('测试关联备注'); joinId = join.join_id; }); test('应该根据ID查找关联', () => { const join = EntityContentJoin.findById(joinId); expect(join).toBeDefined(); expect(join.join_id).toBe(joinId); expect(join.entity_id).toBe(entity1Id); }); test('应该根据实体ID查找关联', () => { const joins = EntityContentJoin.findByEntityId(entity1Id); expect(Array.isArray(joins)).toBe(true); expect(joins.length).toBeGreaterThan(0); expect(joins[0].entity_id).toBe(entity1Id); }); test('应该根据内容ID查找关联', () => { const joins = EntityContentJoin.findByContentId(content1Id); expect(Array.isArray(joins)).toBe(true); expect(joins.length).toBeGreaterThan(0); expect(joins[0].content_id).toBe(content1Id); }); test('应该更新关联', () => { const updatedJoin = EntityContentJoin.update(joinId, { join_note: '更新后的关联备注' }); expect(updatedJoin.join_note).toBe('更新后的关联备注'); }); test('应该获取所有关联', () => { const joins = EntityContentJoin.findAll(); expect(Array.isArray(joins)).toBe(true); expect(joins.length).toBeGreaterThan(0); }); test('应该删除关联', () => { const result = EntityContentJoin.delete(joinId); expect(result.changes).toBe(1); const join = EntityContentJoin.findById(joinId); expect(join).toBeUndefined(); }); test('应该根据实体和内容删除关联', () => { // 重新创建关联 const newJoin = EntityContentJoin.create({ entity_id: entity1Id, content_id: content1Id }); // 删除关联 const result = EntityContentJoin.deleteByEntityAndContent(entity1Id, content1Id); expect(result.changes).toBe(1); // 验证删除 const join = EntityContentJoin.findById(newJoin.join_id); expect(join).toBeUndefined(); }); afterAll(() => { // 清理测试数据 Entity.delete(entity1Id); Content.delete(content1Id); }); });