简体   繁体   中英

How to cover a ManyToOne decorator with Jest?

I have an entity with a @ManyToOne decorator on it. The problem is that my Jest unit test is not covering that single line, even though it cover others decorators.

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:

export const ManyToOne = jest.fn();

How should I write my test with jest so it covers the ManyToOne decorator?

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(); 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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