I have been trying to test my test server using mocha. This is the following code that I use, almost the same as one found in another similar post.
beforeEach(function(done) {
// Setup
console.log('test before function');
ws.on('open', function() {
console.log('worked...');
done();
});
ws.on('close', function() {
console.log('disconnected...');
});
});
afterEach(function(done) {
// Cleanup
if(readyState) {
console.log('disconnecting...');
ws.close();
} else {
// There will not be a connection unless you have done() in beforeEach, socket.on('connect'...)
console.log('no connection to break...');
}
done();
});
describe('WebSocket test', function() {
//assert.equal(response.result, null, 'Successful Authentification');
});
the problem is that when I execute this draft, none of the console.log that is expected to be seen is visible on the command prompt. Can you please explain to me what am I doing wrong?
You have no tests in your example. If there are no tests to be run, then before and after hooks won't be invoked. Try adding a test like:
Georgi is correct that you need an
it
call to specify a test but you don't need to have a top leveldescribe
in your file if you don't want to. You could replace your singledescribe
with a bunch ofit
calls:This works very well if your test suite is small and composed of only one file.
If your test suite is bigger or spread among multiple files, I would very strongly suggest you put your
beforeEach
andafterEach
together with yourit
inside thedescribe
, unless you are absolutely positive that every single test in the suite needs the work done bybeforeEach
orafterEach
. (I've written multiple test suites with Mocha and I've never had abeforeEach
orafterEach
that I needed to run for every single test.) Something like:If you do not put your
beforeEach
andafterEach
insidedescribe
like this, then let's say you have one file to test web sockets and another file to test some database operations. The tests in the file that contains the database operation tests will also have yourbeforeEach
andafterEach
executed before and after them. Putting thebeforeEach
andafterEach
inside thedescribe
like shown above will ensure that they are performed only for your web socket tests.