How can I use setTimeout () functions in Mocha test cases?

I am writing a test in Mocha / Node js and want to use setTimeout to wait for the period before the code block executes.

How can i do this?

It seems that in the test case Mocha setTimeout () does not work. (I know that you can set Timeout for each test case and for each test file, this is not what I need here.)

In js file with Node, i.e. node miniTest.js , this will wait 3 seconds and then print the line inside the setTimeout function.

miniTest.js

 console.log('waiting 3 seconds...'); setTimeout(function() { console.log('waiting over.'); }, 3000); 

In the js file launched with Mocha, i.e. mocha smallTest.js , it will not wait and complete execution and exit without printing a line inside the setTimeout function.

smallTest.js:

 mocha = require('mocha'); describe('small test', function() { it('tiny test case', function() { console.log('waiting 3 seconds...'); setTimeout(function () { console.log('waiting over.') }, 3000); }); }); 
+5
source share
4 answers

You forget to pass the parameter to it('tiny test case', function() and execute the call () after the console.log method in the setTimeout method.

 describe('small test', function(){ it('tiny test case', function(done){ console.log('waiting 3 seconds'); setTimeout(function(){ console.log('waiting over.'); done(); }, 3000) }) }) 
+14
source

Ask your test function to accept a parameter (usually called done ). Mocha will pass the function that you call in the setTimeout function (for example, after console.log call to done() ).

See https://mochajs.org/#asynchronous-code .

+1
source

You should have passed as a parameter in your test, which will be called after passing the test.

You can write your test, for example

 mocha = require('mocha'); describe('small test', function(done) { it('tiny test case', function() { console.log('waiting 3 seconds...'); setTimeout(function () { console.log('waiting over.'); done(); }, 3000); }); 

});

It will wait 3 seconds after that, it will print β€œwait” and pass the test. You can also have a condition inside the timeout, depending on whether the condition is met or not, you can pass the test by calling

 done(); 

or do not run the test, either throwing an error or sending an error message to

 done("Test Failed"); 
+1
source

This is a complete example. You have to call done () in every statement you make. You can leave the before function and setTimeout in one of its functions, but it should use and call done () after the statement.

 var foo = 1; before(function(done) { setTimeout(function(){ foo = 2; done(); }, 500) }); describe("Async setup", function(done){ it("should have foo equal to 2.", function(done){ expect(foo).to.be.equal(2); done(); }); it("should have foo not equal 3.", function(done){ expect(foo).to.be.not.equal(3); done(); }); }); 
+1
source

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


All Articles