FAQ Database Discussion Community


How to make mocha fail when no expect within it()

unit-testing,tdd,mocha,karma-mocha,mocha-phantomjs
Is there an option to set mocha to report test as failing in case no expect provided within it() function? Idea is workflow to be like this: add one it() with desc and callback function the it() is reported as fail since no expectation is set in the callback expectation...

AngularJS, Mocha, Karma. testing controller, mocking service promise

angularjs,promise,mocha,karma-runner,chai
I'm using AngularJS, Karma, Mocha, Chai, Chai-as-promised, Sinon. I'm trying the controller below. I am having trouble mocking the service User and test the .then() sections in the controller. Controller Code .controller('SignupPhoneCtrl', function(User, $scope) { $scope.sendPhoneNumber = function(countryCode, phoneNumber){ User.sendPhoneNumber(countryCode, phoneNumber) .then(function(result){ if(result == "success"){ //I WANT TO TEST THIS...

How do I run tests for a single model using mocha/mean.js?

javascript,mocha,meanjs
I've been looking into mean.js testing. There's a grunt test task that runs all app with a single and easy grunt test, but I don't want to run all tests everytime. I've installed mocha globally, and want to run tests for a single model using it, but doing... mocha 'app/tests/mymodelname.server.model.js'...

Mocha.js --recursive tests fail, but fine as individuals

reactjs,mocha
I've got mocha.opts like this: test/mocha/*.js --recursive --globals reactModulesToStub --check-leaks --compilers .:test/jsx-compiler.js --reporter nyan and there are two tests that pass when called individually, but fail with the recursive option. Am I missing something? For example, if I run mocha on this single test, no problem, but adding a similar...

What does “chainable” in context of testing (mocha, chai) mean?

javascript,testing,mocha,chai
I am new to JavaScript and testing. Only recently I wrote a test for the first time in my life. I am refering to "Chai.js" documentation and it says: The assert style is very similar to node.js' included assert module, with a bit of extra sugar. Of the three style...

Testing a Socket.io app, in which two connections interact

javascript,node.js,socket.io,mocha
I'm very new to unit testing for NodeJS, right now i want to test a socket.io server using Mocha, the app involves the interaction of 2 sockets, the spec is the following var expect = require('expect.js'); var io = require('socket.io-client'); describe("Server", function() { var options = { transports: ['websocket'], 'force...

How to test if two files are identical via mocha

node.js,file,diff,mocha
I have written a node.js script which scans a very large legacy code base and applies a set of changes. The changes can be quite complex because this affects certain storage mechanisms and associated size definitions. I've written tests that all the calculations and reporting is correct by using mocha,...

Using Istanbul and Mocha to cover ES6 code

node.js,code-coverage,mocha,ecmascript-6,istanbul
I have Node code, written in ES6, that I test by issuing mocha --harmony. Tests are fine - everything works. Now I want to add coverage and istanbul to the mix, but I keep getting errors on the first arrow function encountered: No coverage information was collected, exit without writing...

Test in loop mocha

node.js,mocha
I am trying to use data provider in mocha to write less code var should = require('should'); var assert = require('assert'); var request = require('supertest'); var mongoose = require('mongoose'); var winston = require('winston'); var config = require('../app/config'); describe('Authentification', function() { var url = config.web.protocol + '://' + config.web.host + ':'...

Run MochaJS tests on Heroku NodeJS server

node.js,heroku,express,mocha,foreman
I have an extensive MochaJS test suite for my ExpressJS / NodeJS API. The test suite includes creation of objects and removal of those same objects from the database. Currently, all of my regression tests are passing in my development environment. We'd like to be able to run the same...

How do I explicitly fail a unit test using should.js

node.js,mocha,should.js
I'm using Mocha and Should.js to test a promise that I am expecting to generate an error. Because it is a promise, I don't believe I can simply use should.throwError(). This just means that I would like to fail the unit test in the .catch block of the promise. How...

mocha chai expect error

mocha,chai
AssertionError: expected [] to equal [] Expected :[] Actual :[] My test is this: newJobFavored[key].should.equal(favJob[key]); I upgraded all the packages recently and this broke. It appears it should pass if they are two empty arrays....

CLI debugger for Mocha tests

javascript,node.js,debugging,mocha,io.js
I want to be able to drop a debugger statement (or something similar) right into my code and get a REPL when I run my tests so I can interact with my code to debug stuff. I understand that Node (via V8) supports the debugger statement out of the box,...

How to get Mocha to fail a test

javascript,node.js,mocha
I have the following test: it.only('validation should fail', function(done) { var body = { title: "dffdasfsdfsdafddfsadsa", description: "Postman Description", beginDate: now.add(3, 'd').format(), endDate: now.add(4, 'd').format() } var rules = eventsValidation.eventCreationRules(); var valMessages = eventsValidation.eventCreationMessages(); indicative .validateAll(rules, body, valMessages) .then(function(data) { console.log("SHOULD NOT GET HERE"); should.fail("should not get here"); done(); })...

Kicking off mocha describes in parallel

node.js,mocha
I want to be able to have all my describe statements in Mocha get kicked off in parallel. Can someone help me figure out how to do that? Thanks Fizz...

Can't run tests with Mocha on Express.js app

node.js,express,mocha
I am trying to setup mocha to test an ExpressJs app. When I run tests using npm test I got the following error: TypeError: undefined is not a function at Object.<anonymous> (/myapp/bin/www:11:18) at Module._compile (module.js:460:26) at Object.Module._extensions..js (module.js:478:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.cls_wrapMethod (/Users/nathanzylbersztejn/git/airdesk-api/node_modules/newrelic/lib/shimmer.js:230:38) at Module.require (module.js:365:17)...

Mocha beforeEach in one suite is being run in another suite

node.js,mocha
I have two test suites (I am using mocha's TDD UI, which uses suite(), test() rather than describe() and it()): suite('first suite'), function(){ .... }) suite('second suite', function(){ beforeEach(function(done){ console.log('I SHOULD NOT BE RUN') this.timeout(5 * 1000); deleteTestAccount(ordering, function(err){ done(err) }) }) ... }() Running mocha -g 'first suite only...

How to simulate error returned from fs.readFile for testing purposes?

node.js,unit-testing,mocha,fs,chai
I am new to test-driven development and am trying to develop an automated testing suite for my application. I have successfully written tests that verify the data received from a successful call to Node's fs.readFile method, but as you will see in the screenshot below, when I test my coverage...

gulp-mocha how to pass the compilers flag?

javascript,gulp,mocha
I'm trying to use the gulp-mocha module but can't figure out a good way to pass over the compilers flag. Is there a way to include this in my gulp task? Maybe in a separate pipe somehow? Example if running mocha from command line (works fine) mocha --compilers .:my_compiler.js test/**/*.js...

Mocha Loading Blank in Browser

javascript,html,bdd,mocha,chai
Context I've used Mocha before many times, both in the browser and just using the command line. I tend to use Chai's expect module for bdd. I have five test files that have been working with command line npm test. I just want to run the tests in the browser...

How to add a delay before starting a Mocha test case?

javascript,node.js,mongodb,unit-testing,mocha
I'm writing a unit test for my simple Node.js application using Mocha. The application has a class which connects to a Mongo database, fetch the record, and store the formulated record as a field. Simply, the class looks like this: SampleClass.prototype.record = []; // Store the loaded record SampleClass.prototype.init =...

Use SinonJS to stub and spy on the same function?

mocha,sinon
In the following example, I want to stub the get function to prevent the actual HTTP request from occurring. I want to spy on the get method to check what arguments it was called with. var request = require('request'), sinon = require('sinon'); describe('my-lib', function() { sinon.stub(request, 'get').yield(null, null, "{}"); var...

Unable to fail the test by timeout using the mocha with protractor

javascript,testing,mocha,protractor,performance-testing
I found on mocha web site then we can set the timeout fot it blocks, but looks like it doesn't work for me. describe('something', function () { this.timeout(500); it('should take less than 500', function (done) { setTimeout(done, 500); browser.get('#/dashboard'); }); }) Run result: something √ should take less than 500...

Check with Chai if an object doesn't contain any additional properties

node.js,mocha,bdd,chai
I'm working on an API and should return based on permissions only a subset of the actual object's properties. I'm writing my tests in mocha and chai and would like to test for something like this (given res is the response object from the server and res.body contains the received...

What does ^— With additional stack trace in a mocha test mean?

node.js,mocha,sequelize.js
I have a node.js project that is using mocha for it's testing. My most recent test that utilizes Sequelizes create() function for adding a row to a table now produces this message instead of the stack trace that I have always seen up until now... 1) Should be able to...

Mocha - Accessing named functions with ti-mocha

javascript,unit-testing,titanium,mocha
I'm using a hybrid version of mocha, ti-mocha, to build unit test for a Titanium SDK-based app. I'm completely new to BDD and mocha, so the API learning curve is quite steep. Here's my issue with a stripped-down test harness. I can access the index.js module, its methods and properties....

Konacha, Mocha, BackboneJS and Ruby on Rails configuration

ruby-on-rails,ruby,backbone.js,mocha,konacha
I am using Konacha to test a BackboneJS application in my Ruby on Rails application. I have read about every tutorial on the web and it shows how easy it is to set up and get working. Unfortunately, I am not having this level of success. Here is what I...

Sinon catch xmlhttprequest

javascript,jquery,mocha,casperjs,sinon
I have a question concerning Sinon testing. I am using mochacasper and I want to catch the XMLHttpRequest that is sent after I click a button. So far I am not able to catch the request... casper.then(function () { this.fill(...); }); casper.then(function() { this.click('#myButton'); }); casper.then(function () { //I want...

Error: Invariant Violation: dangerouslyRenderMarkup(…): Cannot render markup in a worker thread

reactjs,mocha,jsdom,reactjs-testutils
React Tests Fails after set State causes second render Up until now testing has been going well with JSDOM and Mocha. So far have not had to test any components that change their state. I found my first issue testing a component that changes it's state. The Error 1) Reduced...

React-Router: How to test href of a rendered Link?

javascript,reactjs,mocha,react-router
I have a React component that renders a <Link/>. render: function () { var record = this.props.record; return ( <Link to="record.detail" params={{id:record.id}}> <div>ID: {record.id}</div> <div>Name: {record.name}</div> <div>Status: {record.status}</div> </Link> ); } I can easily obtain the rendered <a/>, but I'm not sure how to test that the href was built...

Access for global variables JavaScript unit testing

javascript,unit-testing,mocha,chai
Hello I am new JavaScript unit testing and I'm using Mocha.js and Chai.js What I want to do is simply figure out how to check the value of a global variable in a seperate js file. Here is my code Here is the main.js file (code to be tested) Just...

Supertest and Mongoose Middleware (post remove)

express,mongoose,mocha,chai,supertest
I have been fiddling with this for days, and I cannot figure out why the Mongoose middleware is not being invoked. So I have an API in node.js and I have a website using Angular.js. The Mongoose middleware is this: schema.post('remove', function (doc) { console.log('doctors - post - remove'); });...

Angular module test not working

angularjs,unit-testing,mocha,karma-runner
I am trying to test an angularjs app. I managed to get some basic test running on my laptop. These tests just check for a module and check some basic functions. This works fine on my laptop. However when I move the testing environment to a local server the tests...

How do I verify the number of elements and content of an array using ParameterMatchers?

ruby,mocha,minitest
I am learning Ruby with TDD using Mocha and MiniTest. I have a class that has one public method and many private methods, so the only method my tests are going to tests are the public one. This public method does some processing and creates an array which is sent...

Allowing chai/mocha tests to bubble errors to process.on

node.js,exception,testing,mocha,chai
I am writing a node module that catches top level uncaught errors and want to write some tests for it. Unfortunately my favorite framework seems to have some issues with intentionally throwing and catching uncaught exceptions. If I throw the exception, it errors and fails the test then. If I...

Karma tests reporting fast runs, but actually running slow

javascript,angularjs,mocha,karma-runner,webpack
This is best explained with a video (or see the gif below): You'll notice that the Karma progress reporter is reporting that the tests are taking milliseconds, but it's obviously taking quite a while... I tweeted about this and was told to Try opening the debug page, and open the...

JavaScript Standard Style does not recognize Mocha

javascript,mocha,js-standard-style
I have a Mocha test file that looks like this: var expect = require('chai').expect var muting = require('../muting') describe('muting', function () { describe('init()', function () { it('should inject an object into twitter', function () { var twitter = 'twitter' muting.init(twitter) expect(muting.twitter).to.equal(twitter) }) }) }) When I run mocha from the...

Mocha Test: Uncaught TypeError: Cannot read property 'status' of null

node.js,tdd,mocha,superagent,expect.js
Learning TDD and my first simple test for my "Hello World" server response is failing in Mocha. I'm using Mocha.js, Superagent, & Expect.js. When I curl -i localhost:8080, I get the correct response and status code. HTTP/1.1 200 OK Content-Type: text/plain Date: Mon, 27 Apr 2015 17:55:36 GMT Connection: keep-alive...

Error: [$injector:unpr] Unknown provider: $stateProvider <- $state

arrays,angularjs,unit-testing,mocha,chai
Executing below unit test gives "Error: [$injector:unpr] Unknown provider: $stateProvider <- $state". I have attached the angular-ui-router.min.js in karma file. describe("Unit tests", function() { var $rootScope, $injector, $state; console.log("hello"); beforeEach(inject(function(_$rootScope_, _$state_, _$injector_, $templateCache) { console.log("hello1"); $rootScope = _$rootScope_; $injector = _$injector_; $state = _$state_; })); describe("states", function() { it("verify state...

Efficiently composing promise tests

javascript,mocha,bluebird
I find myself often writing tests for async APIs like this: beforeEach(function(done) { setup() .then(function(val) { return setup2(); }) .done(done, done); }); it('should test something', function(done) { promiseFunction .then(function(val) { expect(val).to.be.something; }) .done(done, done); }); Which seems pretty straightforward, except for the beforeEach function: if setup2 returns a promise, then...

Angular, Sinon, promises

angularjs,unit-testing,mocha,karma-runner,sinon
Can't get my head around angular, sinon and promises. If I need to test something like this: myCtrl.js angular.module('app') .controller('myCtrl', ($scope, dataService)=> { dataService.list('location').then((lst)=> { $scope.list = lst; }); }); myCtrl-spec.js describe('testing controller', ()=> { var locations = ['A','B','C'], dataService, $scope; beforeEach(module('app')); beforeEach(inject($controller, $rootScope, _dataService_, $q) => { dataService =...

Sinon.js- Trying to spy on console.log but it is already wrapped

javascript,node.js,unit-testing,mocha,sinon
I am new to writing node tests.... this is a my first unit test for a gulp plugin I am trying to write: var chai = require('chai'); var spy = require('chai-spies'); var es = require('event-stream'); var File = require('vinyl'); var mock = require('mock-fs'); var sinon = require('sinon'); var sinonChai =...

Mocha breakpoints using Visual Studio Code

node.js,tdd,mocha,bdd,vscode
Is it possible to add breakpoints to ones Mocha tests using Visual Studio Code? Normally when debugging code one need to configure the launch.json, setting the program attribute to the javascript file to execute. I am not sure how to do this for for Mocha though....

Using should.js how to check whether a string is not present in an array?

javascript,mocha,should.js
Like to check whether a string is present in an array we do someArray.should.contain('str'), but I can't find the negation case check for this.

Understanding enableTimeouts

javascript,timeout,mocha
In mocha 1.21.0, a new setting was introduced enableTimeouts (true/false); and a corresponding --no-timeouts command-line argument. The problem is, it is not documented. Which use cases does it cover? When can it be useful to disable the timeouts?...

Mocha tests taking too long to execute

node.js,mongodb,express,mongoose,mocha
So I'm working on an express.js app where I have a mongoose model User. I wrote a test file (using Mocha) to test the save() function but all of my tests are taking too long to execute and ultimately timeout. Here are the errors I'm getting: Testing - Server -...

How do I test for non-nullness of a property in Chai-as-Promised

node.js,mocha,chai,chai-as-promised
How do I test that an object retrieved from a fulfilled promise has a non-null property? I have a promise that returns an object similar to the following: { id: 1, aDate: 2015-02-12T11:50:00.511Z } I need to check that the aDate property is set and non null. How do I...

Creating a fake object.method() “from scratch” in sinon?

javascript,node.js,mocha,sinon,chai
tl;dr How do you create an object.method() "from scratch" in sinon? the context For example, I have a family of Parser classes where each implements a #parse(text) method and returns a ParseTree object or returns null. I am doing unit testing where I'm not testing Parser objects themselves (they are...

Bypass ESLint's `no-unused-var` for Should in a Mocha test

javascript,mocha,lint,should.js,eslint
I'm using ESLint on all my files, including the test files, with a no-unused-var: true rule. I'm using Should.js in my Mocha tests, and in one of the files, I'm getting an error on the should variable. A quick comparison to the other tests shows, that in other files I...

mocha-phantomjs output not shown when run with Python subprocess.check_output

python,subprocess,phantomjs,mocha,mocha-phantomjs
Guessing this is something to do with STDOUT/STDERR redirection, but the console output is not displayed when running #!/usr/bin/env python import subprocess subprocess.check_output('mocha-phantomjs static/js/tests/headless.html'.split()) The same command in the terminal prints out all the test output...

Backbone.Deferred.Model: Why the unittest is not run?

backbone.js,coffeescript,phantomjs,mocha,chai
Here is the code in question. define (require) -> Backbone = require 'backbone' require 'backbone-deferred' class Data extends Backbone.Deferred.Model urlRoot: 'data' parse: (resp) -> resp.record or resp isValid: -> @get 'valid' # Newly introduced dataUrl: -> @get('data_url')?.replace /abc/, '' And here is the unit test define (require) -> Data =...

Need help in passing this simple mocha test in javascript

node.js,tdd,mocha
Here, I wrote a simple utilities class in Javascript that parses and stringify Json data. //public/js/utilities.js function UtilitiesClass(){ var parserJson = function(obj){ if (typeof(obj) !== "undefined") { return JSON.parse(obj); }; } var stringifyJson = function(obj){ if (typeof(obj) !== "undefined") { return JSON.stringify(obj); }; } } module.exports = UtilitiesClass Then in...

Why is supertest returning an error when everything passes?

javascript,mocha,supertest
My test looks like: it('should create a user with an email address and password', function(done) { return request.post('/v1/users').send(defaultUser).expect(200).expect(function(res) { console.log(res.body); res.body.should.have.property('id'); res.body.should.have.property('name'); res.body.should.have.property('email'); res.body.should.have.property('username'); return res.body.should.have.property('entities')["with"].lengthOf(1); }).end(done); }); res.body looks like { id: 17, name: 'Satoshi Nakamoto', email:...

Gulp mocha crashes nodemon

node.js,tdd,gulp,mocha,nodemon
I have a problem with my mocha gulp task. To run the tests, I have to launch the server, and then run the tests. The problem appears when a test fails : nodemon crashes and the node process still running. Here's my gulpfile: 'use strict'; var gulp = require('gulp'), mocha...

Testing async waterfall with mocha seems to stall

javascript,node.js,asynchronous,mocha
I'm trying to add some mocha testing to a node module I have, but I'm new to it, and my lack of concreteness in terms of callbacks is hampering me. I have tried to pare things back to the most straightforward example, but it's still not working. So my main.js...

Debug remote mocha.js test with node-inspector?

javascript,node.js,mocha,node-inspector
I have a test file on a remote machine and I want to walk through it with node-inspector. So, on the remote machine (Vagrantfile): node-inspector & mocha --debug-brk foo.test.js Then, on my dev machine I open Canary and go to: http://127.0.0.1:8080/debug?ws=127.0.0.1:8080&port=5858 However, I'm not able to debug my test, since...

Unit testing array using items indexes

javascript,unit-testing,mocha,chai
I'm unit testing methods that are applied on an array and change its items states. Those items have different properties. For example, my array is the following : var array = [{state: false}, {status: true}, {health: true}]; After the method is applied (items order is relevant), I'm checking that the...

Chai / Expect - how to work while developing? Seems really hard to go from expect().to.throw to logging the error

javascript,unit-testing,mocha,chai
I have this code expect(function() { //some error }).to.throw(Error); How do I easily go from this to logging the error right here in the test? Do I really have to type try/catch and console.log? Doesn't that go against the fact that I will need to remove them eventually for the...

How to get my node.js mocha test running?

javascript,node.js,mocha,supertest
I have developed a service in node.js and looking to create my first ever mocha test for this in a seperate file test.js, so I can run the test like this: mocha test I could not figure out how to get the reference to my app, routes.js: var _ =...

Run Mocha programatically and pass results to variable or function

javascript,json,node.js,mocha
I've setup a suite of tests in mocha using ZombieJS and Chai. The tests load up a website and check if various services are booked in correctly and are displaying to visitors of the website. What I'm aiming for is that the tests will run daily and then email the...

How to use Webdriver.io with Chai as Promised to verify css property

mocha,chai,webdriver-io,chai-as-promised
Currently using Webdriver.io with Mocha, Chai, and Chai-as-Promised however I am struggling to get the promise to validate when trying to validate a CSS property: The code: 'use strict'; var chai = require('chai'), chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); chai.should(); chaiAsPromised.transferPromiseness = browser.transferPromiseness; describe('Buttons', function() { var buttonSelector = '.button'; browser.url('http://localhost/buttons.html'); it('should...

Nodejs - testing AWS with Mocha

node.js,amazon-web-services,mocha
I'm having trouble writing the tests for the following nodejs code which uses AWS and graphicsmagick. I have tried to search for examples also on how to write tests for async's waterfall method but without any definite results. // dependencies var async = require('async'); var AWS = require('aws-sdk'); var gm...

How can I test through a mocked promise with Mocha?

node.js,unit-testing,mocking,promise,mocha
My node.js code is: function getPatientNotificationNumbers(patientId) { patientId = patientId && patientId.toString(); var sql = "SELECT * FROM [notification_phone_number] "; sql += "WHERE patient_id = " + escapeSql(patientId); return sqlServer.query(sql).then(function(results) { var phoneNumbers = _.map(results[0], function (result) { var obj = { id: result.id, phoneNumber: result.phone_number, isPrimary: result.is_primary, isVerified: result.is_verified,...

How can I test if my Express app's response contains certain HTML tags / text?

node.js,express,mocha,supertest
I'm running an Express Node server, and using Mocha and Supertest to test my routes. I would like to be able to test for the existence of certain text in the response for one of my Express routes, as so: it('should display form text input', function(done) { request(app) .get('/') .end(function...

How do I stub and spy at the same time

javascript,angularjs,unit-testing,mocha,sinon
So I'm testing a function that calls another function, that returns a promise, SUT looks like this: fn($modal) -> modalInstance = $modal.open({ controller: 'myCtrl' size: 'lg' }) modalInstance.result.then(updateData) now If I need to test it I could start with something like this: it 'when modal called, results get updated with...

How can I pass mochas done callback function to another helper function

javascript,callback,promise,mocha
I have a block of code that I will be using several times within a then statement in mocha so I turned it into a function. However I also need to call done()within that function and it's out of scope resulting in the error Uncaught ReferenceError: done is not defined....

Using Q.js promise for unit-tests: timeout of 2000ms exceeded

javascript,unit-testing,asynchronous,mocha,q
I'm using Q.js library for simulating async behaviour by using promise I have a stubed backend api class ApiStub { constructor(){ this.deferred = Q.defer(); } post(url, data) { if (data) { this.deferred.resolve(data); } else { this.deferred.reject(new Error("Invalid data")); } return this.deferred.promise; } } and I'm trying to test it: before(()...

Why is my Mocha reporter double reporting tests?

javascript,html,mocha
I have a custom reporter doc-output.js modified from the doc reporter. /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Doc`. */ exports = module.exports = Doc; /** * Initialize a new `Doc` reporter. * * @param {Runner} runner * @api public */...

Unit Testing Node Script with chai-spy … function spied on is undefined

node.js,unit-testing,gulp,mocha,chai
Writing my first node.js test for my first gulp-plugin....using mocha and chai. I get TypeError: Cannot read property 'Assertion' of undefined for ar errorCheckArg = spy(errorCheckArg);. It seems the errorCheckArg function is not available in the testing enviroment(I did a console.log(errorCheckArg) and it showed undefined). Any idea what I am...

Closing server after mocha test, but data is still there

javascript,node.js,express,mocha
I'm trying to test some data through a REST API. The data is stored as an array in the project. I want the data to be "restored" every time a test suites runs, so that i know the amount of data in the array. But when im testing the post....

NodeJs and Mocha testing the response

angularjs,node.js,mocha
Is it possible to test the response from NodeJs using Mocha? A GET request is made using $http from AngularJs to NodeJs. On success of the request this function is called: var successCallback = function (data) { var SUCCESS_STATUS_CODE = 200; response.set('Content-Type', 'application/json'); response.send({ statusCode: SUCCESS_STATUS_CODE, data: data }); };...

Test succeeding with mocha when it should fail

mocha
There are a few things I don't really get when I execute my mocha test scripts : I am testing about 20 requests, and some of the tests are passing when they shouldn't. For example, I want to retrieve the countries in Europe, the result will be as following :...

How to use “define” with Mocha tests?

javascript,node.js,testing,mocha
I'm getting started with JS testing, and I decided to go with Mocha. The modules I want to test are AMD/RequireJS. However, it seems that Mocha is only compatible with CommonJS modules. So, when I run it, define is not defined. So I've seen this question that suggests this document....

Socket.IO server not receiving message from client

node.js,socket.io,mocha,bdd,expect.js
I'm playing around with Node, Socket.IO and BDD by creating a chat application. During one of the tests, I get a timeout error stating: Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test. The affected test is it('#must be able to receive a message',...

Mocha testing a bluebird powered node style callback

javascript,node.js,mocha,sinon,bluebird
I am facing trouble to get pass a test by running mocha which seems to be passing. The test: describe('.get()',function() { it('should be called once',function() { // => Need to spy on this var callback = function(err,data) { console.log('I am called'); if (err) { console.log('I am logging the error '+err);...

git repository javascript with npm packages

javascript,angularjs,node.js,git,mocha
I am trying to support the how to crack a interview repository.... https://github.com/gaylemcd/ctci/tree/master/javascript/lib/data-structures i am trying to crack the interviews for js position... they are using mocha and chai npms so i am trying to commit the code in js... i looked into one of the examples... not sure...

Using after to clean up in mocha, problems with mongo

node.js,mongodb,coffeescript,mocha
Ok, in the after function console.log "enter after function" and console.log "exit" executes, but console.log "WHYYYY" does not execute. I can't figure out why. For the record, console.log 'insert' does execute. I am making a similar call to mongo in one of my tests, so calling mongo should work. Any...

How to prevent false positives with mocha, promises, and catch blocks

javascript,promise,mocha
I want to take advantage of Mocha's built in promise support, but i'm having difficulty dealing with false positives when I want to test catch branches in my promise chains. This question gets closest to what I want, but the solution requires every developer on my project to add a...

ES6 Promises in Mocha

javascript,mocha,ecmascript-6,chai,es6-promise
I'm using this polyfill for ES6 promises and Mocha / Chai. My assertions for the promises are not working. The following is a sample test: it('should fail', function(done) { new Promise(function(resolve, reject) { resolve(false); }).then(function(result) { assert.equal(result, true); done(); }).catch(function(err) { console.log(err); }); }); When I run this test it...

How to make parts of Protractor wait or become synchronous?

javascript,selenium,jasmine,protractor,mocha
I have code like this in a protractor test, it goes to a home page determines we need to login and then calls this function. Note I'm running this in a NODE.js environment: function Login() { browser.findElement(by.id('ID')).then(function (ele) { ele.sendKeys('SomeUserName'); browser.findElement(by.id('password')).then(function (ele) { ele.sendKeys('SomePassword'); browser.findElement(by.partialButtonText('Sign in')).then(function (ele) { ele.click(); browser.getCurrentUrl().then(function...

How to check velocity is using mirrored data in meteor with mocha

meteor,mocha,meteor-velocity
I am using velocity + mocha for testing my meteor app. On client side when I run test case like below, it is passing. describe("categories server", function(){ it("should return categories", function(done){ setTimeout(done,1500); chai.assert(Cats.find({}).count() > 0); this.timeout(1500); }); But on Client side I'm getting blank collection for the similar test.And in...

Variable isConnected is not changed

javascript,mysql,scope,mocha,chai
isConnected is supposed to be a variable to test if the database connection is successfull or not. Now in my DatabaseTest class I want to assert this isConnected variable. isConnected is declared in the database object, so it should be accessable via database.isConnected. But the value is not changed in...

How can I set up mocha tests to run Ember initializers so injected objects are defined?

ember.js,mocha,testem
My Ember app injects an "i18n" object into the container via an initializer, which is later looked up with "this.container.lookup('i18n:main')" in a controller 'preferredLanguage' computed property. A mocha unit test which tests the controller 'preferredLanguage' property, fails due to "i18n is not defined". How can I set up the mocha...

Testing Express and Mongoose with Mocha

node.js,testing,express,mongoose,mocha
I'm trying to test my REST API endpoint handlers using Mocha and Chai, the application was built using Express and Mongoose. My handlers are mostly of the form: var handler = function (req, res, next) { // Process the request, prepare the variables // Call a Mongoose function Model.operation({'search': 'items'},...

What if there's a global function named “describe” or “it” when using test frameworks like jasmine or mocha [closed]

javascript,jasmine,mocha
It's well known that declaring too many global function or variable is not a good practice. But in Jasmine and Mocha, function like "describe" and "it", why do they prefer global functions? Maybe I havn't fully understood them? Please help!

Created rest ressource in Hapijs

node.js,testing,mocha,hapijs,supertest
I'm building a node REST API server built with hapi.js, for a CRUD ressource, and for the Ressource creation, I want to set the location header and status code using created rather than code(201).header('location.... According the current API Documentation, created(uri) - sets the HTTP status code to Created (201) and...

Sinon - when to use spies/mocks/stubs or just plain assertions?

node.js,unit-testing,tdd,mocha,sinon
I'm trying to understand how Sinon is used properly in a node project. I have gone through examples, and the docs, but I'm still not getting it. I have setup a directory with the following structure to try and work through the various Sinon features and understand where they fit...

How to check assertion error in Mocha when testing async code

node.js,mocha
When testing async code with Mocha and one of my asserts fails, all Mocha does is to report a timeout error. Is there a way to improve this? How to know what asserts failed and why? mocha Contact #getContacts() 1) should return at least 1 contact 0 passing (3s) 1...

Run only one mocha test file on change with gulp

node.js,tdd,mocha,gulp
I have a standard gulp test watcher and runner for my Node.js/mocha setup; gulp.task('mocha', function() { process.env.NODE_ENV = 'test'; return gulp.src(['./test/**/*.js'], {read: false}) .pipe(mocha({recursive: true, reporter: 'list', ui: 'bdd'})) .on('error', gutil.log); }); gulp.task('tests', function() { gulp.watch(sources.concat(tests), ['mocha']); }); I'm wondering how to adapt my watch task (and the other) to...

Estrange behaviour in JavaScript array clone equality assertion

javascript,arrays,unit-testing,mocha,chai
I have found a failing assertion in a JavaScript unit test that I would like to fix. The unit test code is the following (the full code can be found here): beforeEach(function() { arrNeedle = ['waffles']; objNeedle = {w: 'waffles'}; strNeedle = 'waffles'; numNeedle = 3.14159 arrDupe = JSON.parse(JSON.stringify(arrNeedle)); objDupe...

Mocha before and after hooks not executing

node.js,mocha
I am trying to run a simple test on my local cassandra database to check if the select statement returns the correct no of records from the table. However, the code placed between the before and after blocks are not getting called. As a result my test simply fails. var...

How can I unit test node.js functions with Mocha?

node.js,unit-testing,mocking,mocha
I am trying to test a function that looks like: function sendVerifySms(patientId, data) { var smsNumber = data.smsNumber; var verifyCode = ((Math.random() * 1000000) | 0).toString(); var sql = "UPDATE [patient]"; sql += " SET phone_sms_verify_code = '" + verifyCode + "',"; // verification must take place within a one...

Mocha test is not waiting for Publication/Subscription

javascript,testing,meteor,mocha,velocity
Stack Using Mocha + Velocity (0.5.3) for Meteor client-side integration tests. Let's assume that I have autopublish package installed. Problem If a document on the MongoDB was inserted from the server, the client-side mocha tests will not wait for the subscription to synchronise, causing the assertion to fail. Code example...

Excluding files from coverage when using Mocha and Istanbul

node.js,jenkins,mocha,istanbul
How can I exclude folders and files (by path) from coverage report when using mocha and instanbul? I want to exclude by a configuration and not /*istanbul ignore next*/ in each file. (The generated report use by Jenkins) Thanks,...

node.js mocha fallback to debugger on uncaught error

javascript,node.js,debugging,mocha
Is there a way in node.js (ideally mocha too) to simulate the behavior of python python -m pdb setup.py test That will fallback to debug interface on if the program throws an uncaught exception. EDIT @robertklep suggested the undocumented breakOnException command which looks really awesome but not so much in...

Chai expected [Function] to throw an (error) not passing the test (Using Node)

javascript,node.js,unit-testing,mocha,chai
The question: I'm using Chai to do the tests and I seem to be stuck on testing an expected error: Chai expected [Function] to throw an (error) Current code: Here's the code of the test: describe('Do something', function () { it('should remove a record from the table', function (done) {...

Simple mocha testing setup

node.js,mocha
I am using Mocha for testing a Node.js command line app: describe('#call', function () { var nconf = require('nconf'); //is this the best place for this? before(function () { //var nconf = require('nconf'); i'd rather define it here nconf.use('memory'); nconf.set('fp','data_for_testing/csvfile.csv'); nconf.set('mptp','map_ivr_itg'); nconf.set('NODE_ENV','dev_local'); }); it('should run without throwing an error or...

Javascript Mocha Tests - Testing function expressions inside function expressions

javascript,function,testing,mocha,chai
I haven't used Mocha before, so I am a real novice when it comes to testing. However, I wanted to know if it's possible to test a function expression inside of a function expression? I know there are other posts on how you cannot access function expressions inside function declarations...

How to mock a glob call in Node.js

node.js,unit-testing,mocha,sinon,chai
I'm using Mocha, Chai and Sinon JS to write Unit Tests for my Node.js application. Here is the module I want to test: var glob = require('glob'); var pluginInstaller = require('./pluginInstaller'); module.exports = function(app, callback) { 'use strict'; if (!app) { return callback(new Error('App is not defined')); } glob('./plugins/**/plugin.js', function(err,...

Trouble running a scope function in angular test

angularjs,unit-testing,mocha,karma-runner
I have recently started trying to learn how to test angular. I have had some success but at the moment I am trying to test a directive and I cannot seem to make it work. Test code describe('navigation test', function(){ var element, location, route, rootScope, scope, httpBackend; var elm; beforeEach(module('myApp'));...