【发布时间】:2021-07-08 23:05:15
【问题描述】:
我正在使用 HapiJS 开发现有的 NodeJS Web 服务,Hapi Lab 与 Sinon 一起进行测试。该服务使用 massJs 连接到 Postgres 数据库。有一个由其他人实现的方法,它没有单元测试。现在我正在重用这个方法,我想为它实现一些单元测试。 该方法在其内部执行了一个 massjs 事务,持久化到多个表中。
async createSomething(payload) {
const { code, member } = payload;
const foundCompany = await this.rawDb.ethnics.tenants.findOne({ code });
if (foundCompany && foundCompany.companyId) {
const { companyId } = foundCompany;
const { foreignId } = member;
return await this.rawDb.withTransaction(async (tx) => {
const foundMember = await tx.ethnics.members.findOne({ foreign_id: foreignId, company_id: companyId });
if (!foundMember) {
//some business logic...
const newMember = await tx.ethnics.members.insert(member);
//more business logic persisting to other tables...
return newMember;
}
});
}
}
问题是,我不知道如何只在箭头函数内部存根,而不存根整个箭头函数。我只想存根 tx 的调用。我也不想使用数据库,而是存根 rawDb 属性。从单元测试的角度来看,这可行吗?
【问题讨论】:
标签: javascript unit-testing sinon stub