工厂构建的对象的动态值

问题描述 投票:0回答:1

我有一个在测试时构建对象的工厂。下面是代码。正如您所看到的,我有一个私有对象,我将使用该对象来构建工厂返回的对象;我还有构建一个或多个对象的方法:它们只是使用

build_obj
实例化一个对象;其他方法允许我自定义我想要返回的对象:是否希望它关闭、在特定的日期范围内等等。

export class BudgetFactory {
  private build_obj: IBudgetData = {
    id: faker.number.int(),
    title: faker.lorem.sentence(3),
    description: faker.lorem.paragraph(4),
    opening_date: faker.date.future(),
    closing_date: faker.date.future(),
  }

  public getOne(): Budget {
    return new Budget(this.build_obj)
  }

  public getMany(quantity?: number): Array<Budget> {
    let items = []
    for (let i = 0; i < quantity; i++) {
      items.push(this.getOne())
    }
    return items
  }

  public isOnPeriod(opening_date?: Date, closing_date?: Date): this {
    this.build_obj.opening_date = opening_date || faker.date.past()
    this.build_obj.closing_date = closing_date || faker.date.future()

    return this
  }

  public periodIsClosed(opening_date?: Date, closing_date?: Date): this {
    this.build_obj.closing_date = closing_date || faker.date.past()
    this.build_obj.opening_date =
      opening_date || new Date(this.build_obj.closing_date.getTime() - 7 * 24 * 60 * 60 * 1000)

    return this
  }

  public periodIsNotOpenYet(opening_date?: Date, closing_date?: Date): this {
    this.build_obj.opening_date = opening_date || faker.date.future()
    this.build_obj.closing_date =
      closing_date || new Date(this.build_obj.opening_date.getTime() - 7 * 24 * 60 * 60 * 1000)

    return this
  }

  public isClosed(date?: Date): this {
    this.build_obj.closing_date = date || faker.date.past()

    return this
  }
}

关于

getMany
方法只有一个问题:它将返回的对象数组对于每个对象都具有相同的
build_obj
值,因为它是一个属性。我需要一种使用自定义方法来构建对象的方法,但每个对象都必须有自己的值。

typescript oop testing factory
1个回答
0
投票

答案一直就在我眼前。在

getMany
方法中,我只需从类的新实例中调用该方法即可。

  public getMany(quantity: number): Array<Budget> {
    let items = []
    for (let i = 0; i < quantity; i++) {
      items.push(new BudgetFactory().getOne())
    }
    return items
  }
© www.soinside.com 2019 - 2024. All rights reserved.