how to avoid repeating expectations in multiple test when using mocha/chai - mocha.js

I have 20 tests with the same check/expections and I want to reduce the repeated function in the end method call. Any suggestions to refactor?
describe('my test 1', function() {
it('response with email id reference expected', function(done) {
request
.post(apiPath)
.send(input)
.end(function(err, res) {
expect(res.statusCode).equals(200);
expect(res.body.refId.length == 36);
expect(res.body.this1.length = 1);
expect(res.body.that2.length = 2);
expect(res.body.that3.length = 3);
done();
});
});
});

I managed it like this below. If there is better way then please answer.
let positiveAssertions = function(response) {
expect(response.statusCode).equals(200);
expect(response.body.refId.length == 36);
expect(response.body.this1.length = 1);
expect(response.body.that2.length = 2);
expect(response.body.that3.length = 3);
};
describe('my test 1', function() {
it('response with email id reference expected', function(done) {
request
.post(messagingApiPath)
.send(input)
.expect((response) => positiveAssertions(response))
.end(done);
});
});

Related

I tried to maka a QUnit async test for checking ajax update

I tried to maka a QUnit async test for checking ajax update.
I read of QUnit.asyncTest here
https://www.sitepoint.com/test-asynchronous-code-qunit/
but if i try this i get a
TypeError: QUnit.asyncTest is not a function
thats the complete source: https://gist.github.com/232457b002e5363439aece7535600356
of course i new by using QUnit and used JavaScript not for long time.
that a snippet of the part where the error happens:
function max() {
var max = -Infinity;
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
// https://www.sitepoint.com/test-asynchronous-code-qunit/
//TypeError: QUnit.asyncTest is not a function
QUnit.asyncTest('max', function (assert) {
expect(1);
window.setTimeout(function() {
assert.strictEqual(max(3, 1, 2), 3, 'All positive numbers');
QUnit.start();
}, 0);
});
this test gives no syntax error but gives old date:
QUnit.test('usersInnerHTMLlength_Is24', function(assert) {
// problem: this not reads the updates done by ajax. means that are old data:
let innerHTMLlength = $("#users").html().toString().length;
assert.equal(innerHTMLlength, 24);
});
May its not possible to check ajax with QUnit?
I thougt this when i have read here:
QUnit testing AJAX calls
I use it inside a Wordpress Plugin
That sitepoint article is very old (by web standards). You'll need to use the newer syntax found on the documentation website:
function someAsyncThing(value) {
return new Promise(function (resolve, reject) {
setTimeout(function() {
if (value > 5) {
resolve(value);
} else {
reject(new Error("bad value"));
}
}, 500);
});
}
QUnit.test( "some async thing success test", function( assert ) {
// This is what tells QUnit the test is asynchronous
// "done" here will be a callback function used later
var done = assert.async();
// Now call your Async code, passing in a callback...
someAsyncThing(10)
.then(function(result) {
// do your assertions once the async function ends...
assert.equal(result, 10)
// Now tell QUnit you're all done with the test
done();
})
// we can pass the "done" callback from above into catch() to force a test failure
.catch(done);
});
QUnit.test( "some async thing FAILURE test", function( assert ) {
var done = assert.async();
someAsyncThing(4)
.then(function() {
done(new Error("we should NOT succeed with a value < 5"));
})
.catch(function(err) {
assert.equal(err.message, "bad value")
});
});

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves

I have tried to insert the value in db in my mocha test i am getting this error i tried few of the following ways but nothing work out.
var assert=require('chai').assert;
const user=require('../model/user')
i tried both way
describe('insertDataLasone',()=>{
it('should save the value ',(done)=>{
var User = new user({fname:'test'});
User.save().then(done=>{
done()
}).catch(done=>done())
})
})
describe('User', function() {
describe('#save()', function() {
// this.timeout(5000)
it('should save without error', function(done) {
var User5 = new user({fname:'test'});
User5.save(function(done) {
if (err) done(err);
else setTimeout(done,3000);
});
});
});
});
This error occurs when done() is not called in a test. Make sure you are calling done().
var assert = require('chai').assert;
const User = require('../model/user');
describe('insertDataLasone', () => {
it('should save the value ', done => {
var user = new User({ fname: 'test' });
user.save().then(() => {
done();
})
.catch(done); // mocha done accepts Error instance
});
});
or
var assert = require('chai').assert;
const User = require('../model/user');
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user5 = new User({ fname: 'test' });
user5.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
Read https://mochajs.org/#asynchronous-code carefully

Expected undefined to be defined How do i fix it

I am trying to test my Angular with Jasmine but somehow i keep getting this error Expected undefined to be defined and i have followed that angular documentation example i am on mean stack
test.js
describe('Testing Ecdreport Controllers', function(){
var $scope, controller;
var app = angular.module('mean.ecdreport',[])
.controller('EcdreportController', ['$scope', '$http', 'Global', 'Ecdreport', function($scope, $http, Global, Ecdreport) {
$scope.global = Global;
$scope.query = "";
$scope.package = {
name: 'ecdreport'
};
$scope.startDate = null;
$scope.endDate = null;
$scope.currentPage = 1;
$scope.child= [];
$scope.maxSize = 5;
$scope.items = [];
$scope.itemsPerPage = 10;
$scope.totalItems = null;
$scope.direction = 1;
$scope.directionOld = 1;
$scope.sortAttributes = 0;
$scope.sortAttributesOld = 0;
$scope.datamodel = null;
$scope.getDataModel = function() {
$http({url:'/api/v1/getdatamodel', method:"GET"})
.success(function(data) {
console.log('Datamodel successful');
$scope.datamodel = data[0];
console.log('datamodel', data);
})
.error(function(error) {
$scope.datamodel =[];
});
}
// console.log("Trying to get datamodel");
$scope.getDataModel();
});
describe('Testing Ecdreport Controllers', function(){
var $scope, controller;
beforeEach(module('mean.ecdreport', function($controllerProvider){
$controllerProvider.register('EcdreportController', function(){
});
}));
beforeEach(inject(function(_$rootScope_,_$controller_){
$scope = _$rootScope_.$new();
controller = _$controller_('EcdreportController',
{$scope : $scope
});
}));
it('Should be registered', function(){
expect(controller).toBeDefined();
})
it('Testing Scope', function(){
expect($scope).toBeDefined()
expect($Scope.getDataModel).toBeDefined();
})
});
beforeEach(module('mean.ecdreport', function($controllerProvider){
$controllerProvider.register('EcdreportController', function(){
});
}));
beforeEach(inject(function(_$rootScope_,_$controller_){
$scope = _$rootScope_.$new();
controller = _$controller_('EcdreportController',
{$scope : $scope
});
}));
it('Should be registered', function(){
expect(controller).toBeDefined();
})
it('Testing Scope', function(){
expect($scope).toBeDefined()
expect($scope.getDataModel).toBeDefined();
})
});
You get that error because your controller in test is never defined. You need to use var controller = ...
You should use controller injection like this :
beforeEach(inject(function(_$rootScope_,_$controller_){
$scope = _$rootScope_.$new();
createController = function() {
return _$controller_('EcdreportController', {
$scope : $scope
});
};
}));
and initialize the controller in each test like this :
it('Should be registered', function(){
var controller = new createController();
expect(controller).toBeDefined();
})
This way you can also pass on different parameters in each test if your controller requires any data to be passed on to.

how to use .cancel() with bluebird

document API here http://bluebirdjs.com/docs/api/cancellation.html
i try it in my demo,but doesn't work
var Promise = require('bluebird');
var a = require('./a');
var b = require('./b');
var cancelPromise = Promise.resolve();
cancelPromise.cancel();
cancelPromise = a.fnA()
.then(function() {
return b.fnB();
})
.then(function() {
console.log('done');
})
.finally(function() {
if (cancelPromise.isCancelled()) {
console.log('canceled');
}
console.log('end');
});
so how to use this method?
To use .cancel(), first you need to turn cancellation ON and only then call function .cancel()
If your work with bluebird below 3, your code should look something like that:
var mainAction = a.fnA()
.cancellable() // => cancellation turned on
.then(function() {
return b.fnB();
})
.then(function() {
console.log('done');
})
.catch(function( err ){ // => 'Reason for cancel'
console.error(err);
})
.finally(function() {
console.log('end');
});
mainAction.cancel('Reason for cancel');
And if you work with bluebird 3 and above, the code should look like this:
var successfulFetch = false, mainAction = a.fnA()
.then(function() {
return b.fnB();
})
.then(function() {
console.log('done');
}).finally(function() {
if(!successfulFetch){
console.error('Reason for cancel');
}
console.log('end');
});
mainAction.cancel();
Also I suggest you to take a look at this post: Cancel a delayed Bluebird promise
which was really helpful for me, when I had a similar problem

AngularJS: Using $q to fire ajax calls synchronously

Is it possible to use $q to fire ajax requests synchronously in AngularJS?
I have a long list of vehicles, each vehicle has events associated with them and I need to retrieve the eventdetails of each event when the user expands the listing.
Right now, if the user expands the listing, I am firing up to 15 calls asynchronously and it seems to be causing issues with the API I'm consuming, so I'd like to see if performance is improved if I wait for each request finishes before firing the next.
I'm attempting to implement $q to delay the next request until the previous is finished, however I can't seem to wrap my head around using the service, here is what I currently have:
// On click on the event detail expander
$scope.grabEventDetails = function(dataReady, index) {
if (dataReady == false) {
retrieveEventDetails($scope.vehicles[index].events);
}
}
var retrieveEventDetails = function(events) {
// events is array
var deferred = $q.defer();
var promise = deferred.promise;
var retrieveData = function(data) {
return $http({
url: '/api/eventdetails',
method: 'POST',
data: {
event_number: data.number
},
isArray: true
});
}
_.each(events, function(single_event) {
promise.then(retrieveData(single_event).success(function(data) {
console.log(data);
}));
});
}
This is still firing asynchronously, Where am I going wrong with this?
I understand firing the requests synchronously isn't the best idea, at the moment I just want to see if performance is improved with the API at all.
You don't need $q to implement a promise as $http returns one.
_.each fires all the callbacks without especially waiting the promise.
All you do is call retrieveData for all events whenever your promise is resolved, and since you don't do a first call, it shouldn't even be working
You could do some recursive call like this :
var retrieveEventDetails = function(events) {
var evt = events.shift();
$http({
url: '/api/eventdetails',
method: 'POST',
data: {
event_number: evt.number
},
isArray: true
}).then(function(response){
console.log(response.data);
retrieveEventDetails(events);
});
}
I do think you should use $q as some other part of your application might need to get a promise.
A good example would be $routeProvider resolve option.
I made a little demo in plunker.
Solution:
retrieveData function should return a function (which returns a promise) instead of a just a promise.
That way we can create a promise chain: promise.then(fn).then(fn).then(fn).then(null,errorFn)
We must resolve the first promise to kick the chain.
var retrieveEventDetails = function(events) {
// events is array
var deferred = $q.defer();
var promise = deferred.promise;
var retrieveData = function(data) {
return function(){
return $http({
url: '/api/eventdetails',
method: 'POST',
data: {
event_number: data.number
},
isArray: true
})
}
}
deferred.resolve();
return events.reduce(function(promise, single_event){
return promise.then(retrieveData(single_event));
}, promise);
}
I'm not sure you even need $q here. In this example, each piece of data is registered in the controller as soon as it comes back from the call.
Live demo (click).
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, myService) {
$scope.datas = myService.get();
});
app.factory('myService', function($http) {
var myService = {
get: function() {
var datas = {};
var i=0;
var length = 4;
makeCall(i, length, datas);
return datas;
}
}
function makeCall(i, length, datas) {
if (i < length) {
$http.get('test.text').then(function(resp) {
datas[i] = resp.data+i;
++i;
makeCall(i, length, datas);
});
}
}
return myService;
});
Here's a way using $q.all() that you can wait for all of the data to come through before passing it to the controller: Live demo (click).
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, myService) {
myService.get().then(function(datas) {
$scope.datas = datas;
})
});
app.factory('myService', function($q, $http) {
var myService = {
get: function() {
var deferred = $q.defer();
var defs = [];
var promises = [];
var i=0;
var length = 4;
for(var j=0; j<length; ++j) {
defs[j] = $q.defer();
promises[j] = defs[j].promise;
}
makeCall(i, length, defs);
$q.all(promises).then(function(datas) {
deferred.resolve(datas);
});
return deferred.promise;
}
}
function makeCall(i, length, defs) {
if (i < length) {
$http.get('test.text').then(function(resp) {
defs[i].resolve(resp.data+i);
++i;
makeCall(i, length, defs);
})
}
}
return myService;
});

Resources