Jest mocking类型Orm链接函数

bwleehnv  于 2023-06-20  发布在  Jest
关注(0)|答案(1)|浏览(110)

我在express项目中使用typeorm,我对使用jest进行单元测试非常陌生。我正在努力用jest测试typeorm的链接方法。如果你能帮忙的话我会很感激的

仓库.ts

export function getRepository(entity: any): Repository<any> {
    try {
        return MySQLDataSource.getRepository(entity);
    } catch (e) {
        throw new AuthServiceException(`Error occurred when finding ${entity} repository`);
    }
}

测试文件(RoleRepository.ts)

class RoleRepository {

    private repository: Repository<Role>;

    public constructor() {
        this.repository = getRepository(Role);
    }

    public async findByRole(role: RoleType): Promise<Role | null> {
        try {
            return await this.repository.createQueryBuilder().select("Role")
            .where("role.role=:role", {role: role})
            .getOne();
        } catch (e) {
            throw new AuthServiceException("Error occurred when finding role by rolename from DB");
        }
    }
}

module.exports = RoleRepository;

测试文件(RoleRepository.test.ts

const RoleRepository = require('../../src/repository/RoleRepository');

jest.mock('../../src/repository/Repository', () => {
    return {
        getRepository: jest.fn(),
    }
});

const role = new Role();
role.setProperty(EntityProperty.ID, "rid-123");
let mockedGetRepository: jest.Mock;
let RoleRepositoryInstance: typeof RoleRepository;
mockedGetRepository = getRepository as jest.Mock;

describe('RoleRepository, findByRole method test', () => {
    let mockedFindByRole: jest.Mock;

    beforeEach(() => {
        mockedFindByRole = jest.fn();
        mockedGetRepository.mockReturnValue({
            createQueryBuilder: mockedFindByRole,
        });
        RoleRepositoryInstance = new RoleRepository();
    });

    test('Should return role, when finding by role is successful', async () => {

        mockedFindByRole.mockResolvedValue(role);

        const result = await RoleRepositoryInstance.findByRole(RoleType.USER);
        expect(result).toBe(role);
        expect(result.getProperty(EntityProperty.ID)).toBe("rid-123")
    });
})

在线错误

const result = await RoleRepositoryInstance.findByRole(RoleType.USER);

AuthServiceException: Error occurred when finding role by rolename from DBJest

cwtwac6a

cwtwac6a1#

使用mockFn.mockReturnThis()模拟方法链调用。
例如
Role.entity.ts

import { Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Role {
  @PrimaryGeneratedColumn()
  id: number;
}

export enum RoleType {
  USER = 'user',
}

Repository.ts

export function getRepository(entity: any): any {
  // real implementation
}

RoleRepository.ts

import { Repository } from 'typeorm';
import { getRepository } from './Repository';
import { Role, RoleType } from './Role.entity';

class RoleRepository {
  private repository: Repository<Role>;

  public constructor() {
    this.repository = getRepository(Role);
  }

  public async findByRole(role: RoleType): Promise<Role | null> {
    return await this.repository.createQueryBuilder().select('Role').where('role.role=:role', { role: role }).getOne();
  }
}

export default RoleRepository;

RoleRepository.test.ts

import { getRepository } from './Repository';
import { Role, RoleType } from './Role.entity';
import RoleRepository from './RoleRepository';

jest.mock('./Repository');

const getRepositoryMock = getRepository as jest.Mock;

describe('RoleRepository, findByRole method test', () => {
  test('Should return role, when finding by role is successful', async () => {
    const role = new Role();
    role.id = 123;

    const RepositoryMock = {
      createQueryBuilder: jest.fn().mockReturnThis(),
      select: jest.fn().mockReturnThis(),
      where: jest.fn().mockReturnThis(),
      getOne: jest.fn().mockResolvedValue(role),
    };
    getRepositoryMock.mockReturnValue(RepositoryMock);

    const roleRepositoryInstance = new RoleRepository();
    const result = await roleRepositoryInstance.findByRole(RoleType.USER);
    expect(result).toEqual(role);
  });
});

测试结果:

PASS  stackoverflow/76501346/RoleRepository.test.ts
  RoleRepository, findByRole method test
    ✓ Should return role, when finding by role is successful (3 ms)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |     100 |      100 |   83.33 |     100 |                   
 Repository.ts     |     100 |      100 |       0 |     100 |                   
 Role.entity.ts    |     100 |      100 |     100 |     100 |                   
 RoleRepository.ts |     100 |      100 |     100 |     100 |                   
-------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.141 s

软件包版本:

"typeorm": "^0.3.16",
"jest": "^29.5.0",
"typescript": "^5.1.3"

相关问题