微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – 如何使用Mocha测试模拟的承诺?

我的node.js代码是:

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’},我猜这是一个解决的承诺.

所以我到处都是,我愿意使用任何图书馆让事情变得简单.我没有嘲笑,罪恶或其他什么.任何建议都会有帮助.

谢谢!

解决方法

因此,另一种方法是使用 rewirederide的组合.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐