瀏覽代碼

fix unit tests and complete em.getModelFor method with exception

Olivier Massot 1 年之前
父節點
當前提交
35ad7061ed
共有 2 個文件被更改,包括 27 次插入14 次删除
  1. 6 1
      services/data/entityManager.ts
  2. 21 13
      tests/units/services/data/entityManager.test.ts

+ 6 - 1
services/data/entityManager.ts

@@ -87,7 +87,12 @@ class EntityManager {
    *
    * @param entityName
    */
-  public async getModelFor(entityName: string): Promise<typeof ApiResource> {
+  public async getModelFor(
+    entityName: string,
+  ): Promise<typeof ApiResource> {
+    if (!Object.prototype.hasOwnProperty.call(modelsIndex, entityName)) {
+      throw new Error("No model found for entity name '" + entityName + "'")
+    }
     return await modelsIndex[entityName]()
   }
 

+ 21 - 13
tests/units/services/data/entityManager.test.ts

@@ -50,13 +50,13 @@ const _console: any = {
 
 vi.mock('~/models/models', async () => {
   class MyModel {
-    static entity = 'myModel'
+    static entity = 'my-model'
   }
 
-  const models: Record<string, any> = { myModel: MyModel }
+  const modelsIndex: Record<string, any> = { 'my-model': () => MyModel }
 
   return {
-    default: models,
+    default: modelsIndex,
   }
 })
 
@@ -134,27 +134,35 @@ describe('cast', () => {
 })
 
 describe('getModelFor', () => {
-  test('simple call', () => {
-    expect(entityManager.getModelFor('myModel').entity).toEqual('myModel')
+  test('simple call', async () => {
+    const model = await entityManager.getModelFor('my-model')
+    expect(model!.entity).toEqual('my-model')
+  })
+  test('non existing model', async () => {
+    expect(
+      async () => await entityManager.getModelFor('non-existing-model'),
+    ).rejects.toThrowError(
+      "No model found for entity name 'non-existing-model'",
+    )
   })
 })
 
 describe('getModelFromIri', () => {
-  test('simple call', () => {
+  test('simple call', async () => {
     // @ts-ignore
-    entityManager.getModelFor = vi.fn((entityName: string) =>
-      entityName === 'dummy' ? DummyApiResource : null,
+    entityManager.getModelFor = vi.fn(
+      async (entityName: string) => DummyApiResource,
     )
 
     // @ts-ignore
-    const result = entityManager.getModelFromIri('/api/dummy/123')
-
+    const result = await entityManager.getModelFromIri('/api/dummy/123')
+    console.log(result)
     expect(result).toEqual(DummyApiResource)
   })
   test('invalide Iri', () => {
-    expect(() => entityManager.getModelFromIri('/invalid')).toThrowError(
-      'cannot parse the IRI',
-    )
+    expect(
+      async () => await entityManager.getModelFromIri('/invalid'),
+    ).rejects.toThrowError('cannot parse the IRI')
   })
 })