如何使用sinon存根对象方法?

问题描述 投票:0回答:1

我需要存根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: {...}
        });
    }
    ...
}
node.js sinon
1个回答
1
投票

您当前的方法为sendMandrill工厂创建的每个实例创建一个新的mailHandler。实际上你应该把它叫做没有新的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存根原型属性,并证明使用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() {} })
© www.soinside.com 2019 - 2024. All rights reserved.