node.js - 在 Mocha/Chai/Sinon 中存根 DB 连接线
问题描述
我的代码中有以下行有问题
测试控制器.ts
static async getTest(req:any, res:any, next:object) {
console.log("BEGIN -- TestController.getTest");
let testid = req.params.testid;
let query = `SELECT * FROM TEST WHERE TEST_ID = :1`;
let binds: string[] = [testid];
let result = await ConnectionDB.executeSimpleQuery(query, binds);
}
我现在正在 Test.ts 中运行测试,我正在执行以下操作
测试.ts
it('Get Order method', function () {
let req = {params: {testid: 12345}};
let res = {
status: '200'
};
//const dbConn = sinon.stub(xxxx, "xxxxxx").returns(true);
TestController.getTest(req, res, Object);
});
我总是在有 ConnectionDB.executeSimpleQuery(query, binds); 的行中出现错误。所以我想把它存根并返回一个示例 json 响应,我不知道如何用 Sinon 做到这一点。
解决方案
您可以使用sinon.stub()
为ConnectionDB.executeSimpleQuery
方法制作存根。
例如
controller.ts
:
import { ConnectionDB } from './db';
export class Controller {
static async getTest(req: any, res: any, next: object) {
console.log('BEGIN -- TestController.getTest');
let testid = req.params.testid;
let query = `SELECT * FROM TEST WHERE TEST_ID = :1`;
let binds: string[] = [testid];
let result = await ConnectionDB.executeSimpleQuery(query, binds);
console.log(result);
}
}
db.ts
:
export class ConnectionDB {
static async executeSimpleQuery(query, bindings) {
return { message: 'real' };
}
}
controller.test.ts
:
import { ConnectionDB } from './db';
import { Controller } from './controller';
import sinon from 'sinon';
describe('61617621', () => {
it('should pass', async () => {
const logSpy = sinon.spy(console, 'log');
const json = { message: 'fake' };
const executeSimpleQueryStub = sinon.stub(ConnectionDB, 'executeSimpleQuery').resolves(json);
const mReq = { params: { testid: 1 } };
const mRes = {};
const mNext = {};
await Controller.getTest(mReq, mRes, mNext);
sinon.assert.calledWithExactly(executeSimpleQueryStub, 'SELECT * FROM TEST WHERE TEST_ID = :1', [1]);
sinon.assert.calledWithExactly(logSpy, { message: 'fake' });
});
});
带有覆盖率报告的单元测试结果:
61617621
BEGIN -- TestController.getTest
{ message: 'fake' }
✓ should pass
1 passing (18ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 90 | 100 | 50 | 90 |
controller.ts | 100 | 100 | 100 | 100 |
db.ts | 50 | 100 | 0 | 50 | 3
---------------|---------|----------|---------|---------|-------------------
推荐阅读
- python - django 查询没有正确分组
- c++ - 有必要使用std::move吗?这不是已经是右值引用了吗?
- r - 如何使用另一个数据框中的字段值调用包含列的值
- visual-studio-2015 - 我的 android 设备没有在 Visual Studio 2015 上检测到 xamarin 表单
- java - java.lang.IndexOutOfBoundsException 在不应该达到索引时嵌套for循环
- shell - 如何单击 Xpath 元素并使用 shell 脚本下载 csv 文档?
- python - 如何在 Boto3 中正确创建和附加 ELB
- vb.net - 如何拆分字符串而不是字符?
- react-native - 得到一个错误,说一个道具不是一个函数,而且它是未定义的
- javascript - 在 Express.js 中提供资产时遇到问题