javascript - 如何为箭头函数内的逻辑正确创建单元测试
问题描述
我正在使用 HapiJS、Hapi Lab 与 Sinon 一起开发现有的 NodeJS Web 服务以进行测试。该服务使用 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 属性。从单元测试的角度来看,这可行吗?
解决方案
是的,这是可行的。有 2 种选择:
- 直接存根 MassiveJS 方法。
存根大量方法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'));
- 使用内存中的 pg 进行测试。
仅出于测试目的,您可以使用以下模块:test-pg-pool或pg-mem。在测试之前,启动测试 pg 并在测试完成后销毁它。
推荐阅读
- wordpress - 将引导表添加到 WordPress
- javascript - 鉴于与 IOS 不兼容,WebRTC getUserMedia 存在哪些替代方案?
- java - 使用更快的算法按值对 TreeMap 进行排序
- python - KeyError : 1 在为日期集进行替换值时发生
- python - 计数排序实现只工作了一半
- javascript - 覆盖 javascript
- python - Django:没有反向匹配。如何反转到上一个 URL?
- excel - 如何对另一列的值唯一的一列中的值进行计数?
- javascript - getServerSideProps 函数响应无法在 Next.js 中序列化为 JSON
- html - 将模板转换为纯 CSS 网格