诗乃用 Sequelize 模拟

Sinon mocking with Sequelize

我有以下使用 Sequelize 的 nodejs 函数:

var processDatabase = function (dbConnection, schema, recordsets) {

    var myLogTable = dbConnection.define(schema.tableName, schema.myLogSchema, schema.myLogSchemaIndex);
    myLogTable.sync({

        force: false,
        freezeTableName: true,
        logging: console.log

    }).then(function () {

        console.log('Table synced...');

        for (k = 0; k < recordsets.length; k++) {

            var query = "Some query";

            dbConnection.query(
                    query, {
                        type: dbConnection.QueryTypes.SELECT
                    }
                )
                .then(function (results) {
                    console.log('MYSQL Selection Done');
                })
                .catch(function (err) {
                    console.log('MYSQL Error: ' + err.message);
                });
        }
    }).catch(function (err) {
        console.log('MYSQL Sync Error: ' + err.message);
    });
};

我是 mocking 的新手,并不是特别了解如何测试 catch 部分。

这是我可以想出的单元测试,但我不知道同步调用如何转到捕获部分:

describe('when call processDatabase', function () {

    it('should process successfully when sync fails', function (done) {

        seqConnection.define = function (tableName, schema, schemaIndex) {
            return mockMyLogModel;
        };

        processProfilesNotMapped(seqConnection, {
                        tableName: 'SomeTable',
                        myLogSchema: myLogSchema,
                        myLogSchemaIndex: myLogSchemaIndex
                    }, []);
        done();         
    })
});

我应该如何编写我的 mocking 以便我可以同时测试 catch 和覆盖它们?

您需要在 mock 中延迟异常,因为 "sync" 使用 promises。您可以使用 q 库或任何其他库。这样当你执行 sync 函数时,它会转到 catch 部分
使用 q 的示例:

describe('when call processDatabase', function () {

    it('should process successfully when sync fails', function (done) {

        seqConnection.define = function (tableName, schema, schemaIndex) {
            const mock = {
                sync: function(){
                   const deferred = q.defer();
                   deferred.reject(new Error('Some error'));
                   return deferred.promise;
                }
            }
            return mock;
        };

    expect(
        function(){
            cmdManager.execute("getProfileDummy","hosar@gmail.com")
        }
    ).to.throw(Error);

        processProfilesNotMapped(seqConnection, {
                        tableName: 'SomeTable',
                        myLogSchema: myLogSchema,
                        myLogSchemaIndex: myLogSchemaIndex
                    }, []);
        done();         
    })
});