universo-platform-3d

Форк
0
160 строк · 4.4 Кб
1
import { Provider, Type } from '@nestjs/common'
2
import { getModelToken } from '@nestjs/mongoose'
3
import { Model } from 'mongoose'
4
import { vi } from 'vitest'
5
import { CreateScriptEntityDto } from '../../src/script-entity/dto/create-script-entity.dto'
6
import { UpdateScriptEntityDto } from '../../src/script-entity/dto/update-script-entity.dto'
7
import { ScriptEntityDocument } from '../../src/script-entity/script-entity.schema'
8
import { MockMongooseClass } from './mongoose-module.mock'
9

10
/**
11
* @description This is used as a convenience to mock many classes in the providers array. It results in:
12
{
13
  provide: ZoneService,
14
  useClass: createViMockClass(ZoneService)
15
},
16
{
17
  provide: SpaceService,
18
  useClass: createViMockClass(SpaceService)
19
},
20
{
21
  provide: SpaceObjectService,
22
  useClass: createViMockClass(SpaceObjectService)
23
}
24

25
Then in providers, it can be used as
26
...getMockClassesForProvidersArray([ZoneService, SpaceService, SpaceObjectService])
27
* @date 2023-07-03 18:07
28
*/
29
export function getMockClassesForProvidersArray(classes: any[]): Provider[] {
30
  return classes.map((c: any) => {
31
    return {
32
      provide: c,
33
      useValue: createViMockClass(c)
34
    }
35
  })
36
}
37

38
export function createViMockClass(targetClass: Type<any>): Type<any> {
39
  const propertyNames = Object.getOwnPropertyNames(targetClass.prototype)
40

41
  for (const propertyName of propertyNames) {
42
    const propertyValue = targetClass.prototype[propertyName]
43

44
    if (typeof propertyValue === 'function') {
45
      targetClass.prototype[propertyName] = vi.fn()
46
    }
47
  }
48

49
  return targetClass
50
}
51

52
/**
53
* @description Similar to the above, this results in
54
    [{
55
      provide: getModelToken('Zone'),
56
      useValue: MockMongooseClass
57
    },
58
    {
59
      provide: getModelToken('Terrain'),
60
      useValue: MockMongooseClass
61
    }]
62
* @date 2023-07-03 18:09
63
*/
64
export function getMockMongooseModelsForProvidersArray(
65
  modelNames: string[] = [
66
    // The default list here is everything, which will cover most use caes
67
    'Asset',
68
    'CustomData',
69
    'Environment',
70
    'MapAsset',
71
    'Material',
72
    'Role',
73
    'Space',
74
    'SpaceObject',
75
    'SpaceVariable',
76
    'SpaceVariablesData',
77
    'SpaceVersion',
78
    'Terrain',
79
    'Texture',
80
    'User',
81
    'UserAccessKey',
82
    'UserEntityAction',
83
    'PurchaseOption'
84
  ]
85
): Provider[] {
86
  return modelNames.map((c: any) => {
87
    return {
88
      provide: getModelToken(c),
89
      useClass: MockMongooseClass
90
    }
91
  })
92
}
93

94
/**
95
 * ScriptEntityService
96
 */
97
export class MockScriptEntityService {
98
  private scriptEntities: ScriptEntityDocument[] = []
99
  private readonly model: Model<ScriptEntityDocument>
100

101
  constructor() {
102
    this.model = {
103
      create: vi.fn().mockResolvedValue(null),
104
      findById: vi.fn().mockImplementation((id: string) => {
105
        const found = this.scriptEntities.find((entity) => entity._id === id)
106
        return Promise.resolve(found || null)
107
      }),
108
      findByIdAndUpdate: vi
109
        .fn()
110
        .mockImplementation((id: string, update: any) => {
111
          const found = this.scriptEntities.find((entity) => entity._id === id)
112
          if (found) {
113
            const updated = { ...found, ...update }
114
            this.scriptEntities = this.scriptEntities.map((entity) =>
115
              entity._id === id ? updated : entity
116
            )
117
            return Promise.resolve(updated)
118
          }
119
          return Promise.resolve(null)
120
        }),
121
      findOneAndDelete: vi.fn().mockImplementation((condition: any) => {
122
        const found = this.scriptEntities.find(
123
          (entity) => entity._id === condition._id
124
        )
125
        if (found) {
126
          this.scriptEntities = this.scriptEntities.filter(
127
            (entity) => entity._id !== condition._id
128
          )
129
          return Promise.resolve(found)
130
        }
131
        return Promise.resolve(null)
132
      })
133
    } as unknown as Model<ScriptEntityDocument>
134
  }
135

136
  create(
137
    createScriptEntityDto: CreateScriptEntityDto
138
  ): Promise<ScriptEntityDocument> {
139
    const created: ScriptEntityDocument = {
140
      _id: (this.scriptEntities.length + 1).toString(),
141
      ...createScriptEntityDto
142
    } as ScriptEntityDocument
143
    this.scriptEntities.push(created)
144
    return Promise.resolve(created)
145
  }
146

147
  findOne(id: string) {
148
    return this.model.findById(id)
149
  }
150

151
  update(id: string, updateScriptEntityDto: UpdateScriptEntityDto) {
152
    return this.model.findByIdAndUpdate(id, updateScriptEntityDto, {
153
      new: true
154
    })
155
  }
156

157
  delete(id: string) {
158
    return this.model.findOneAndDelete({ _id: id })
159
  }
160
}
161

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.