I need to test the server, but on the local machine, the functionality of sending letters does not work, so to send letters you need to make a stub using SinonJS.

The problem is that for the first time I encountered such a task and testing. In principle, what I figured out, but when it comes to the realization of the problem, I can’t figure out exactly where to create the mock and how to create it.

Maybe someone has illustrative code examples or someone can show me exactly how to do it?

Here is the function that needs to be locked, it should send a letter to activate the account, but on the local machine it does not need to be configured, just need to somehow make a stub.

var originalFunction = function(event){ return Bb .try(() => { let templateData = { appName: config.app.title, name: event.user.name, token: event.user.emailVerificationToken }; return verificationTpl(templateData); }) .then(function (emailHtml) { var mailOptions = _.extend({ to: event.user.username, html: emailHtml }, verificationEmailOptions, emailConfig.options); log.info('Sending mail to: ' + mailOptions.to); var retValue = emailConfig.transport.sendMailAsync(mailOptions); return retValue; }) .catch((err) => { log.error('Cannot send mail: ' + err); }); }; 
  • one
    Add to the question a description of the specific object that you want to mock. Without this specifics, you can only advise reading the documentation, since the question is too general - Dmitriy Simushev

1 answer 1

In the current form, you can correctly test just one fact: the originalFunction function is called with the correct parameters. And you can do it like this:

 let sinon = require('sinon'), should = require('should'), stub = sinon.stub(); // Заглушка всегда будет возвращать выполненное обещание. stub.returns(Promise.resolve()); // Передавайте заглушку вашему модулю, и выполняйте над ним действия, приводящие // к отправке почты. По завершению этих действий, выполните проверку // аргументов. Не забудьте об АСИНХРОННОСТИ. // Пример тестируемого модуля. let m = new Module(stub); m.doSomething().then(() => { // Функция должна быть вызвана... stub.calledOnce.should.be.true(); // ... с правильным аргументом. let firstCall = stub.getCall(0); firstCall.arg.should.be.eql({ user: { name: 'foo', emailVerificationToken: 'bar' } }); }); 

Comment:

Yes, if you wish, you can also use the global variables log , config , emailConfig and others, but this is a road to nowhere. Instead of normal unit tests, you get a set of indistinct code, strongly linked with the implementation of the originalFunction . And to make truly unit tests you need to throw out all global variables and pass dependencies explicitly.

  • Thanks for the example, but the stub must be done not for the incoming danich's functions, but rather instead of the function, since sending a letter leads to errors on this machine, I just need to make sure that the values ​​of the successful function return from the function, despite what happens inside - pj-infest
  • one
    @ pj-infest, Well, so who's stopping you from returning everything you want to stub.returns ? You understand that when it comes to tests , all that you can test is the right arguments. And if you just need a stub , then you need a simple anonymous function of the form () => Promise.resolve({field: 'data'}) . Sinon is not needed here - Dmitriy Simushev