2016-11-07 88 views
1

嘲笑我使用Sequelize以下功能的NodeJS:兴农与Sequelize

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

我是新来的嘲讽,不特别知道如何测试扣部分。

这是我的单元测试,我可以想出,但我不知道呼叫如何同步可以去捕捉部分:

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

我怎么会写我的嘲讽,这样我可以测试两个捕获,然后,以便他们可以被覆盖?

回答

1

由于“同步”使用承诺,您需要推迟模拟中的异常。您可以使用q库或任何其他。通过这种方式,当您执行同步功能时,它将转到捕捉部分
使用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","[email protected]") 
     } 
    ).to.throw(Error); 

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