Just started to learn JavaScript, I need your help:

describe('Test Suite #1', function(){ it('Check URL Errors', function() { assert.equal(checkStatusCode(URL), true); }); }); 

The problem with assert.equal(...) is that the comparison is done before the function is completed. The question is how to get around this moment? How are such moments resolved when I need to get the result of a function, and then perform actions with it? Do you need promises for this or are there other options?

Thank!

@vp_arth, but do not tell me with an example, how to make a nodejs-style function with a callback from this?

 function checkStatusCode(url, cb){ if (url == 'right url'){ cb(null, true); } else{cb(null, false);} } 
  • This is solved by either synchronous mocks of asynchronous functions (ajax, timeout), or asynchronous tests. - vp_arth
  • Why do you even try to check what the function returns? How would you get the result of this function without tests? - vp_arth
  • No, this function is written specifically for the test. In fact, this test was initially ideologically incorrect. My question is more likely not to a specific implementation here, but in principle, about how to get the result of one function and use it in another, without putting them into each other. - marchcorpse
  • What does it mean in any way? We do not know what is written there. If return new Promise(...) is one thing, if function(url, next) is another. My question is what do you call the result of a function ? - vp_arth
  • In such cases, you need to use promises - JavaJunior

1 answer 1

Asynchronous tests are written in mocha quite simply:

 describe('Test Suite #1', function(){ it('Check URL Errors (promise-style function)', function(done) { checkStatusCode(URL) .then(function(res) { assert.equal(res, true); done(); }); }); it('Check URL Errors (nodejs-callback style function)', function(done) { checkStatusCode(URL, function(err, res) { if (err) done(err); assert.true(res); done(); }); }); }); 
  • Thank! Tell me, please, and with what it is connected, what happens when using the second option: 'Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done ()" is called; if returning a promise, ensure it resolves' - marchcorpse
  • A timeout error is triggered if done has not been called. Just your function is not a nodejs-style function with a callback: function(url, cb) { ... cb(null, true); ... } function(url, cb) { ... cb(null, true); ... } - vp_arth