node.js - MySQL 连接:TypeError:connection.query 不是函数
问题描述
我正在为需要数据库连接的方法编写单个单元测试。我试图用 sinon.mock 来模拟它,但是我被抛出:
TypeError: connection.query is not a function
为什么会发生这种情况,模拟不应该只适合我的条件并执行功能吗?我不关心它会返回什么,我只关心它是否会执行某事。你能告诉我如何正确重构它吗?我现在不需要存根,我只想测试我的函数在不同条件下的行为。
测试用例:
const sinon = require('sinon');
const chai = require('chai');
chai.use(require('sinon-chai'));
chai.use(require('chai-as-promised'));
const {Connection} = require('mysql');
...OTHER IMPORTS
describe('queries', () => {
let connectionMock;
before(() => {
connectionMock = sinon.mock(Connection);
});
describe('TEST CASE', () => {
const partialProp = {
id: 1,
date: '2019-08-23',
};
const accoId = 11;
it('TEST CASE v1', async () => {
const getSpy = sinon.spy(getAcco);
const prop = {...partialProp, accoId, cpId: null};
await getProp(prop, connectionMock);
chai.expect(getSpy).to.have.been.calledWith(prop, sinon.match.any);
});
});
});
测试代码:
export const getProp = async (prop, connection) => {
if (prop.accoId !== null) {
const acco = await getAcco(prop.accoId!, connection); <-- this fails because uses connection.query from mysql
} else {
....
}
};
export const getAcco = async (id, connection) => {
return new Promise((resolve, reject) => {
connection.query(MY_QUERY_STRING, parameters, (err, result: any) => {
if (err) {
console.error('db error', err);
reject(new Error('Error communicating with database.'));
} else {
resolve(result);
}
});
});
}
解决方案
推荐阅读
- html - 导航菜单没有出现在顶部
- javascript - 在 React 中定义样式时无法更改按钮位置
- android - 如何保存片段状态
- javascript - 使用nodejs方法socket.write将所有数据发送到哪里?
- java - 我如何在springboot中使用休息模板来保存新对象
- rabbitmq - 带有 MQTT 的 RabbitMQ 在连接时发送消息
- sql - Postgresql:一行中多行的值
- android-studio - 无法使用导入包中的成员 (Flutter)
- python - python selenium phantomjs 执行脚本
- ansible - 在 Ansible Tower 上获取部署次数