【发布时间】:2022-03-13 19:37:26
【问题描述】:
我正在为 NestJS 应用程序编写 UT。 我在模拟甚至测试事务内部函数的逻辑时遇到问题。
这是来自服务的一段代码,它获取连接并开始使用 transactionEntityManager 与 DB 交互。
我希望像这个例子一样测试一个函数的内部逻辑(我有几个这样的案例)。
import { getConnection } from 'typeorm';
@Injectable()
export class UsersService {
async getUsers(user: User): Promise<{ users: User[], organizations: MinimalOrg[] }> {
const result: { users: User[], organizations: MinimalOrg[] } = { users: [], organizations: [] };
// getConnection() is imported from 'typeorm'
await getConnection().transaction(async (transactionEntityManager) => {
if (!user || !Utils.isAdmin(user)) {
throw new UnauthorizedException('You have no permission');
}
result.users = await transactionEntityManager
.createQueryBuilder(User, 'user')
.leftJoin('user.image', 'image')
.leftJoin('user.organization', 'organization')
.select([
'user.id',
'user.email',
])
.addSelect(['organization.id', 'organization.name'])
.addSelect(['image.id', 'image.fileName'])
.getMany();
result.organizations = (await transactionEntityManager
.createQueryBuilder(Organization, 'org')
.select(['org.id', 'org.name'])
.getMany()) as MinimalOrg[];
});
return result;
}
}
我已经尝试在单元测试中使用这种方法,但无法成功。
jest.mock('typeorm',()=>({
transaction:jest.fn()
}));
任何帮助将不胜感激
【问题讨论】:
-
如果这个问题有更多的重点,会更容易回答;也许选择一个您正在尝试编写的测试并编辑问题以询问这个问题?
-
乍一看,您是从 typeorm 模拟
transaction,而您只是在代码中导入getConnection。 -
至少,如果你想模拟交易,你需要类似:
({ getConnection: () => ({ transaction: jest.fn() }) })in your jest.mock -
关于焦点:如果我模拟
geConnection().transaction(,我如何才能访问最简单的行if (!user || !Utils.isAdmin(user)) {以及如何模拟像getConnection()这样的全局函数来实现这一点? -
出于好奇,为什么使用
typeorm中的getConnection()而不是@nestjs/typeorm中的@InjectConnection()来注入连接并能够在(嵌套)约定中模拟它?
标签: typescript unit-testing jestjs nestjs typeorm