简体   繁体   English

如何用 Jest 覆盖多对一装饰器?

[英]How to cover a ManyToOne decorator with Jest?

I have an entity with a @ManyToOne decorator on it.我有一个带有 @ManyToOne 装饰器的实体。 The problem is that my Jest unit test is not covering that single line, even though it cover others decorators.问题是我的 Jest 单元测试没有覆盖那一行,即使它覆盖了其他装饰器。

The entity (Simplified):实体(简体):

@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;

The typeorm is also mocked in a __mocks__ folder, exporting the properties used, including: typeorm也在__mocks__文件夹中__mocks__ ,导出使用的属性,包括:

export const ManyToOne = jest.fn();

How should I write my test with jest so it covers the ManyToOne decorator?我应该如何开玩笑地编写我的测试,以便它涵盖 ManyToOne 装饰器?

My guess is that the non-covered line is not the entire line with the decorator, but only the body of the callback.我的猜测是未覆盖的行不是带有装饰器的整行,而只是回调的主体。

Since you have mocked const ManyToOne = jest.fn();因为你已经嘲笑了const ManyToOne = jest.fn(); your decorator is a function that does not have implementation and does not invokes any passed callback.您的装饰器是一个没有实现且不调用任何传递的回调的函数。

So if you mock it as a function which immediately executes and returns the result of the given callback因此,如果您将其模拟为一个立即执行并返回给定回调结果的函数

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

you should be able to achieve 100% coverage of that line您应该能够实现该线路的 100% 覆盖率

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM