Sinon嘲笑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); }); }; 

我是新来的嘲笑,并不特别知道如何testing捕捉部分。

这是我可以提出的unit testing,但我不知道如何调用同步可以进入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(); }) }); 

我怎么会写我的嘲笑,以便我可以testing两个捕获,然后也可以被覆盖?

你需要在你的模拟中推迟一个exception,因为“同步”使用的是承诺 。 您可以使用q库或任何其他。 这样,当你执行同步function时,它将进入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(); }) });