An easy way to write synchronization functions in node.js

For testing purposes, my code will look better if I can perform some testing functions that expect synchronization for their results.

I know the basic ideas about event programming in node.js, but during tests that run with synchronous processor locking, this is not a problem for me.

Is there any simple (one-line, better) solution for executing a function that returns some values ​​using the callback method (err, ret), to return ret using "return" and pretend that execution is synchronous.

+4
source share
2 answers

You can use node -sync for this purpose https://github.com/0ctave/node-sync

But overall, I would recommend that you do not. For example, a mocha testing platform allows you to run asynchronous tests. Also async waterfall https://github.com/caolan/async#waterfall is a good way to pseudo-sync code.

I would say stay in an asynchronous mind. Even when testing.

+5
source

Mocha has a built-in callback done to make this happen. The model I use for my code is:

 describe('some spec', function () { beforeEach(function (done) { // common spec initalization code.. common.init (function (err, stuff) { done(err); }); }); describe('particular case', function () { var result, another; beforeEach(function (done) { // case init 1.. case.init(function (err, res) { result = res; done(err); }); }); beforeEach(function (done) { // case init 2.. case.init2(function (err, res) { another = res; done(err); }); }); it ('should be smth', function () { expect(result).to.equal(0); }); it ('should be smth else', function () { expect(another).to.equal(1); }); }); }); 
0
source

Source: https://habr.com/ru/post/1498153/


All Articles