【问题标题】:How to cover a ManyToOne decorator with Jest?如何用 Jest 覆盖 ManyToOne 装饰器?
【发布时间】:2020-04-24 09:30:35
【问题描述】:

我有一个带有@ManyToOne 装饰器的实体。问题是我的 Jest 单元测试没有覆盖那一行,即使它覆盖了其他装饰器。

实体(简体):

@Entity({ name: 'user' })
export default class User {
  @PrimaryGeneratedColumn('uuid')
  public id: string;

  @Column({ name: 'username' })
  @IsNotEmpty()
  @MinLength(3)
  @MaxLength(30)
  public username: string;

  @ManyToOne(() => Account)
  @IsNotEmpty()
  @JoinColumn({ name: 'account_id', referencedColumnName: 'id' })
  public account: Account;

typeorm 也在 __mocks__ 文件夹中模拟,导出使用的属性,包括:

export const ManyToOne = jest.fn();

我应该如何用 jest 编写测试以覆盖 ManyToOne 装饰器?

【问题讨论】:

    标签: typescript jestjs typeorm test-coverage


    【解决方案1】:

    我的猜测是,未覆盖的行不是装饰器的整行,而只是回调的主体。

    由于您已经模拟了const ManyToOne = jest.fn();,您的装饰器是一个没有实现并且不调用任何传递的回调的函数。

    因此,如果您将其模拟为一个立即执行并返回给定回调结果的函数

    export const ManyToOne = jest.fn(callback => callback());
    

    你应该能够实现 100% 的覆盖率

    【讨论】:

    • 完美。这是有道理的,因为这个装饰器是唯一一个接收回调作为参数的装饰器
    猜你喜欢
    • 2020-03-03
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 2017-04-09
    • 2021-12-27
    相关资源
    最近更新 更多