我的node.js代码是: function getPatientNotificationNumbers(patientId) { patientId = patientId patientId.toString(); var sql = "SELECT * FROM [notification_phone_number] "; sql += "WHERE patient_id = " + escapeSql(patientId); return sq
function getPatientNotificationNumbers(patientId) { patientId = patientId && patientId.toString(); var sql = "SELECT * FROM [notification_phone_number] "; sql += "WHERE patient_id = " + escapeSql(patientId); return sqlServer.query(sql).then(function(results) { var phoneNumbers = _.map(results[0], function (result) { var obj = { id: result.id, phoneNumber: result.phone_number, isPrimary: result.is_primary, isVerified: result.is_verified, patientId: result.patient_id } return obj; }); return phoneNumbers; }); }
非常简单直接.我想测试的是,正确解析的这个函数的返回是一个与该格式匹配的phoneNumbers数组.
sqlServer是上面要求的,我在这个文件中有很多要求.为了把它们排除在外,我正在使用嘲弄,这看起来非常棒.
到目前为止,这是我的测试:
before(function() { deferred = Q.defer(); mockery.enable(); moduleConfig.init(); mockery.registerSubstitute('moment', moment); mockery.registerAllowable('../../util'); mockStubs.sqlServer = { query: sinon.stub().returns(deferred.promise) } mockery.registerMock('../../db/sqlserver', mockStubs.sqlServer); methods = require('../../../rpc/patient/methods'); }); beforeEach(function() { deferred = Q.defer(); }) it('should get the patient notification numbers', function(done) { // sinon.spy(sqlServer, 'query').and.returnValue(deferred.promise); deferred.resolve('here we go'); methods.getPatientNotificationNumbers(1).then(function(result) { console.log(result); done(); }); });
但是,它永远不会超过我的代码中的sqlServer.query.所以结果毫无意义.我也试过类似的东西:
response = methods.getPatientNotificationNumbers(1)
但是当我在console.log(响应)时,它基本上是{state:’pending’},我猜这是一个未解决的承诺.
所以我到处都是,我愿意使用任何图书馆让事情变得简单.我没有嘲笑,罪恶或其他什么.任何建议都会有帮助.
谢谢!
因此,另一种方法是使用 rewire和 deride的组合.var should = require('should-promised'); var rewire = require('rewire'); var Somefile = rewire('./path/to/file'); var deride = require('deride'); var sut, mockSql; before(function() { mockSql = deride.stub(['query']); Somefile.__set__('sqlServer', mockSql); sut = new Somefile(); }); describe('getting patient notification numbers', function() { beforeEach(function() { mockSql.setup.query.toResolveWith(fakeSqlResponse); }); it('resolves the promise', function() { sut.getPatientNotificationNumbers(id).should.be.fulfilledWith(expectedPhoneNumbers); }); it('queries Sql', function(done) { sut.getPatientNotificationNumbers(id).then(function() { mockSql.expect.query.called.once(); done(); }); }); });
这意味着您不需要更改生产代码,并且可以使用以下内容轻松地开始测试不快乐的路径:
it('handles Sql errors', function(done) { mockSql.setup.query.toRejectWith(new Error('Booom')); sut.getPatientNotificationNumbers(id) .then(function(){ done('should not have resolved'); }) .catch(function(e) { e.should.be.an.Error; e.message.should.eql('Booom'); done(); }); });
或者甚至更简洁:
it('handles Sql errors', function(done) { mockSql.setup.query.toRejectWith(new Error('Booom')); sut.getPatientNotificationNumbers(id).should.be.rejectedWith(/Booom/); });