Mocha runs only one test - node.js

I have a sails.js app that I want to test with mocha, in my test folder I have 2 tests, but when I run mocha only one test gets executed.
Test1.js
var request = require('supertest');
describe.only('UserController', function() {
describe('#login()', function() {
it('should redirect to /mypage', function (done) {
done();
});
});
});
Test2.js
describe.only('UsersModel', function() {
describe('#find()', function() {
it('should check find function', function (done) {
done();
});
});
});
I run tests with this command:
./node_modules/.bin/mocha
Output
UserController
#login()
✓ should redirect to /mypage
1 passing (10ms)
Please explain me my mistake.

It is because you are running an exclusive test by using describe.only(). Use describe() instead.
See exclusive tests in the mocha documentation

Related

Jasmine-node tests always pass

I'm new to BDD and for some reason my code always seem to be passing although I haven't yet written any code. Can somebody please explain why this is happening?
Project setup:
I have a project folder with package.json and a test section with the following declared: ".node_modules/.bin/jasmine-node" and a folder called spec with the following code file:
var request = require("request");
describe("Web Server Test", function() {
it("GET /", function(done) {
request.get("http://localhost/", function(error, request, body) {
expect(body).toContain("Hello, World!");
});
done();
});
});
This is the output I get:
C:\Users\\OneDrive\Documents\Websites\Projects\Node\project>npm
test spec/app_spec.js
Project#0.0.0 test
C:\Users\\OneDrive\Documents\Websites\Projects\Node\project
jasmine-node "spec/app_spec.js"
.
Finished in 0.031 seconds 1 test, 0 assertions, 0 failures, 0 skipped
the done callback must be called inside request callback...
it("GET /", function(done) {
request.get("http://localhost/", function(error, request, body) {
expect(body).toContain("Hello, World!");
// THIS IS ASYNC
done();
});
});

Testing express with Mocha: a promise-based test will not run by itself?

I have two test files. When only test1.js is present, no tests run, and mocha reports "0 passing" tests. When test1.js and test2.js are present but both depend on a promise, then still no tests run and mocha still reports "0 passing". But when one of the tests is modified to not use a promise, mocha runs both tests and they succeed. What the heck? Here are my files:
index.js:
require('./server').then( function(server) {
server.listen(8080, function() {
console.log("Started server");
});
);
server.js:
var express = require('express');
var server = express();
module.exports = new Promise((function(resolve, reject) {
return resolve(server);
}));
test1.spec.js:
require('./server').then(function(server) {
describe('Test Suite #1', function () {
it('should run test #1', function testSomething(done) {
return done();
});
});
});
test2.spec.js (server.js used as promise, tests do not run):
require('./server').then(function(server) {
describe('Test Suite #2', function () {
it('should run test #2', function testSomethingElse(done) {
return done();
});
});
});
test2.spec.js (server.js not used as promise, both tests run):
var server = require('./server');
describe('Test Suite #2', function () {
it('should run test #2', function testSomethingElse(done) {
return done();
});
});
To run them, I just have nodejs, express, and mocha installed and run:
% mocha "*.spec.*"
I understand I'm not using the server variable in these examples, but of course the real tests need to return a promise because sometimes the server.js is accessing remote systems for config data. I could work around this, but any help in understanding what's happening here would be greatly appreciated!
You need to describe and define all your tests synchronous. Otherwise they aren't recognized by mocha. If you have some async setup to make, use the before or beforeEach functions:
describe('Test Suite #1', function () {
var server;
before(function(done){
require('./server').then(aServer => {
server = aServer;
done();
});
});
it('should run test #1', function testSomething(done) {
return done();
});
});

Mocha - Which runs first, beforeEach or before?

I have a web app with a spec like this:
describe('Hook them up', () => {
var server;
beforeEach(done => {
server = app.listen(done);
});
before(done => {
// Does this run before or after "beforeEach"
// If I try to access the api at this point I get an ECONNREFUSED
});
after(done => {
server.close(done);
});
it('should set the \'createdAt\' property for \'DndUsers\' objects', done => {
api.post('/api/tweets')
.send({ text: 'Hello World' })
.then(done)
.catch(err => {
console.log(err);
done();
});
});
});
In some other project of mine, if I try to access the api in the before block it works fine, as if the beforeEach was already run.
See my answer here to a very similar question.
Mocha's test runner explains this functionality the best in the Hooks section of the Mocha Test Runner.
From the Hooks section:
describe('hooks', function() {
before(function() {
// runs before all tests in this block
});
after(function() {
// runs after all tests in this block
});
beforeEach(function() {
// runs before each test in this block
});
afterEach(function() {
// runs after each test in this block
});
// test cases
it(...); // Test 1
it(...); // Test 2
});
You can nest these routines within other describe blocks which can also have before/beforeEach routines.
This should give you
hooks
before
beforeEach
Test 1
afterEach
beforeEach
Test 2
afterEach
after

How do I launch server for multiple mocha chai-http test files?

I am starting my node server in my before block on my mocha chai-http tests.
I have it working perfect for single test files. However when I attempt to run multiple tests in a single command NODE_ENV=test mocha test/**/*.js I am getting an error.
I tried to have the node servers launch on different ports per test file. This didn't work, got node server start errors.
I'm now thinking it would be great if I can have a single mocha file that runs before my other test files to start the server and then a single file that runs after the other test files to kill/stop the server.
How would I go about this.
Below is some of my code:
Here is one of my test files for reference:
var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
var Sails = require('sails');
describe('REST User API', function() {
var app; // for access to the http app
var sails; // for starting and stopping the sails server
before(function (done) {
Sails.lift({
port: 3001,
log: {
level: 'error'
}
}, function (_err, _sails) {
if(_err){
console.log("Error!", _err);
done();
}
else {
app = _sails.hooks.http.app;
sails = _sails;
done();
}
});
});
describe("user session", function () {
var res; // http response
var authenticatedUser;
before(function (done) {
chai.request(app)
.post('/users/signin')
.set('Accept', 'application/json')
.set('Content-Type', 'application/json')
.send({ email: 'admin#test.com', password: 'secret'})
.end(function (_res) {
res = _res; // Record the response for the tests.
authenticatedUser = JSON.parse(_res.text); // Save the response user for authenticated tests
done();
});
});
it("should connect with a 200 status", function () {
expect(res).to.have.status(200);
});
it("should have a complete user session", function () {
var userSession = authenticatedUser;
expect(userSession).to.have.property('firstName');
expect(userSession).to.have.property('lastName');
expect(userSession).to.have.property('gender');
expect(userSession).to.have.property('locale');
expect(userSession).to.have.property('timezone');
expect(userSession).to.have.property('picture');
expect(userSession).to.have.property('phone');
expect(userSession).to.have.property('email');
expect(userSession).to.have.property('username');
expect(userSession).to.have.property('confirmed');
expect(userSession).to.have.property('status');
expect(userSession).to.have.property('authToken');
});
});
after(function (done) {
sails.lower(function() {
done()
});
});
});
From mocha v8.2.0, you can use GLOBAL FIXTURES to setup and teardown your web server for all test suites. Global fixtures are guaranteed to execute once and only once.

Mocha beforeEach and afterEach during testing

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?
Georgi is correct that you need an it call to specify a test but you don't need to have a top level describe in your file if you don't want to. You could replace your single describe with a bunch of it calls:
it("first", function () {
// Whatever test.
});
it("second", function () {
// Whatever other test.
});
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 and afterEach together with your it inside the describe, unless you are absolutely positive that every single test in the suite needs the work done by beforeEach or afterEach. (I've written multiple test suites with Mocha and I've never had a beforeEach or afterEach that I needed to run for every single test.) Something like:
describe('WebSocket test', function() {
beforeEach(function(done) {
// ...
});
afterEach(function(done) {
// ...
});
it('response should be null', function() {
assert.equal(response.result, null, 'Successful Authentification');
});
});
If you do not put your beforeEach and afterEach inside describe 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 your beforeEach and afterEach executed before and after them. Putting the beforeEach and afterEach inside the describe like shown above will ensure that they are performed only for your web socket tests.
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:
describe('WebSocket test', function() {
it('should run test and invoke hooks', function(done) {
assert.equal(1,1);
done();
});
});
You need to have a test-callback(eg. it) inside suite-callback(eg, describe) to execute beforeEach() and afterEach() hooks. More info https://mochajs.org/#run-cycle-overview

Resources