mysql连接:typeerror:connection.query不是函数

yyyllmsg  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(267)

我正在为采用数据库连接的方法编写单单元测试。我试图用sinon来模拟它。但是我被扔了:

TypeError: connection.query is not a function

为什么会发生这种情况,mock不应该只适合我的条件并执行函数吗?我不在乎它会返回什么,我只在乎它是否会执行某些东西。你能告诉我如何正确地重构它吗?我现在不需要存根,我只想测试我的函数在不同条件下的行为。
测试用例:

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);
            }
        });
    });
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题