我正在开发一个现有的NodeJS web服务,它使用HapiJS、HapiJS和Sinon一起进行测试。该服务使用massiveJs连接到Postgres。有一个由其他人实现的方法,它没有单元测试。现在我正在重用这个方法,我想为它实现一些单元测试。该方法在其中执行一个massivejs事务,并持久化到多个表。
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属性的存根。从单元测试的角度来看,这是可行的吗?
发布于 2021-05-05 22:06:05
是的是可行的。有两种选择:
存根大量方法findOne的示例
const massive = require('massive');
const sinon = require('sinon');
// Stub massive.Readable class method findOne.
// You need to find where is the real method findOne and stub it.
const stub = sinon.stub(massive.Readable, 'findOne');
// You can resolve it.
stub.resolves();
// Or you can throw it.
stub.throws(new Error('xxx'));https://stackoverflow.com/questions/67082570
复制相似问题