繁体   English   中英

如何用sinon存根对象方法?

[英]How to stub an object method with sinon?

我需要存根mh对象的sendMandrill方法。

查看我的测试文件(mail.js):

let MailHandler = require('../../modules/mail.handler.module');
...
let api = (router, parser) => {
   let send = async (req, res, next) => {
      let mh = new MailHandler();
      mh.sendMandrill();    
      ...
   }
   ...    
   return router.post('/mail/send', parser.json(), send);
}
module.exports = api;
...

我的测试(mail.spec.js):

let stRequest = require('supertest');
let MailHandler = require('../../modules/mail.handler.module');
describe('my test', () => {
   beforeEach(() => {
      sinon.stub(MailHandler.prototype, 'sendMandrill', () => true);
   })
   it('stubs sendMandrill!', done => {
      stRequest(app)
         .post('/mail/send')
            .end((err, resp) => {
                done();
            });
   })
})

目前,我得到以下错误:

TypeError: Cannot stub non-existent own property sendMandrill

添加mail.handler.module-参见下面的mailHandler / sendMandrill代码:

module.exports = mailHandler;

function mailHandler() {
    ...
    var mandrill = require('../modules/mandrill');

    var handler = {
        sendMandrill: sendMandrill,
        ...
    };

    return handler;

    function sendMandrill() {
        mandrill.messages.sendTemplate({
            message: {...}
        });
    }
    ...
}

您当前的方法为mailHandler工厂创建的每个实例创建一个新的sendMandrill 实际上,您应该不使用new let mh = mailHandler()调用它,甚至最好将其重命名为createMailHandler以避免滥用。

如果要有效地使用原型继承,则需要重写mailHandler以实际使用this而不是新创建的对象。

var mandrill = require('../modules/mandrill');

module.exports = MailHandler;

function MailHandler() {
    // use this instead of newly created object
    this.foo = 'bar'

    // avoid explicit return
    // return handler;
}

// set methods to prototype
MailHandler.prototype.sendMandrill = function sendMandrill() {
        // use this instead of handler here
        mandrill.messages.sendTemplate({
            message: {...}
        });
    }

使用上述方法,您将能够通过sinon对原型属性进行sinon并证明使用new关键字调用构造函数是合理的。

UPD

如果你无法控制mail.handler.module你既可以使用rewire模块,允许嘲弄整个依赖性或暴露MailHandler作为您的一部分api模块,使其注射。

api.MailHandler = require('../../modules/mail.handler.module')

let mh = api.MailHandler();

然后在测试中

let oldMailHandler;

beforeAll(() => { oldMailHandler = api.MailHandler})
afterAll(() => { api.MailHandler = oldMailHandler})
beforeEach(() => { api.MailHandler = function MockMailHandler() {} })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM