我在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
1条答案
按热度按时间cwtwac6a1#
使用
mockFn.mockReturnThis()
模拟方法链调用。例如
Role.entity.ts
:Repository.ts
:RoleRepository.ts
:RoleRepository.test.ts
:测试结果:
软件包版本: