首页 > 解决方案 > 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);
            }
        });
    });
}

标签: node.jsmockingchaisinonsinon-chai

解决方案


推荐阅读