it('Check the row count', function () {
module.verifyTableTitle().getText().then(function (Title) {
expect(Title).toBe('ABC');
module.verifyexcel().isPresent().then(function (firstExcel) {
downloadex.verifyExcel('Excel1.xlsx');
**console.log("rowcount :"+rowObject1");**
}
this.verifyExcel = function (filename) {
let workbook = new Excel.Workbook();
browser.driver.wait(function () {
return files.existsSync(downloadDirectory + '\\' + filename);
}, 3000).then(function rowExcel() {
switch (filename) {
case 'Excel1.xlsx'':
let worksheet = workbook.getWorksheet("Excel1");
let rowObject1 = worksheet.rowCount;
console.log("rowcount :"+rowObject1);
});
return rowObject1;
});
break;
how to get the rowcount of excel sheet from verifyExcel function(console.log("rowcount :"+rowObject1)) to top function.
You can pass that variable as argument of top function, example:
const f1 = (arg) => {
console.log(arg);
}
const f2 = () => {
let rowcount = "test";
f1(rowcount);
}
f2();
f1();
declare a variable with var or let on top of your describe block and simply use in any of it blocks under the spec.
e.g.- please refer the sample-
import { browser } from 'protractor';
var yourVariable
describe('Info API: ', function () {
browser.ignoreSynchronization = true; // for non-angular websites
it('This is test ', function (done) {
your code;//use ur variable here
});
it('This is test1 ', function (done) {
your code;//use ur variable here
});
});
This is my basic JS to concatenate two strings, the context.getVariable is something which I want to mock using Sinon,
//util.js
var p;
function concat(p) {
var first_name = context.getVariable('first_name');
var res = p.concat(first_name);
return res;
}
concat(p);
I have added this test.js,
var expect = require('expect.js');
var sinon = require('sinon');
var rewire = require('rewire');
var app = rewire('./util.js');
var fakeContext = {
getVariable: function(s) {}
}
var contextGetVariableMethod;
beforeEach(function () {
contextGetVariableMethod = sinon.stub(fakeContext, 'getVariable');
});
afterEach(function() {
contextGetVariableMethod.restore();
});
describe('feature: concat', function() {
it('should concat two strings', function() {
contextGetVariableMethod.withArgs('first_name').returns("SS");
app.__set__('context', fakeContext);
var concat = app.__get__('concat');
expect(concat("988")).to.equal("988SS");
});
});
I am running,
node_modules.bin> mocha R:\abc\js-unit-test\test.js
util.js:7
var first_name = context.getVariable('first_name');
^
TypeError: context.getVariable is not a function
You need to import actual context here and then use sinon.stub to mock that getVariable method so it it will get that method when your actual code is running.
var expect = require('expect.js');
var sinon = require('sinon');
var rewire = require('rewire');
var context = require('context') // give correct path here
var app = rewire('./util.js');
var fakeContext = {
getVariable: function(s) {}
}
beforeEach(function () {
contextGetVariableMethod = sinon.stub(context, 'getVariable');
});
afterEach(function() {
contextGetVariableMethod.restore();
});
describe('feature: concat', function() {
it('should concat two strings', function() {
contextGetVariableMethod.withArgs('first_name').returns("SS");
var concat = app.__get__('concat');
expect(concat("988")).to.equal("988SS");
});
});
Here is the code I am writing tests for:
'use strict';
var internals = {};
var _ = require('lodash');
module.exports = {
initialize: function (query) {
internals.query = query;
},
createField: function (fieldId, accountId, payload) {
function callQuery (parList) {
var query = 'INSERT into fields VALUES (:uuid, :accountId, :shortcutName, :displayName, :fieldType, :widgetType, :columnOrder, :options, :required, NULL)';
return internals.query(query, parList, function () { return fieldId; });
}
var increment = 10;
var parameterList = {
'uuid': fieldId,
'accountId': accountId,
'shortcutName': payload.shortcutName,
'displayName': payload.displayName,
'fieldType': payload.fieldType,
'widgetType': payload.widgetType,
'columnOrder': payload.columnOrder,
'options': JSON.stringify(payload.options) || null,
'required': payload.required || 'f'
};
if (!payload.columnOrder) {
var columnQuery = 'SELECT MAX(column_order) from fields';
return internals.query(columnQuery, {}, function (x) {return x; })
.then(function (results) {
var highestColumnOrder = results[0]['MAX(column_order)'];
var newHighestColumnOrder = Math.ceil(highestColumnOrder / 10) * 10;
if (newHighestColumnOrder > highestColumnOrder) {
parameterList.columnOrder = newHighestColumnOrder;
} else {
parameterList.columnOrder = newHighestColumnOrder + increment;
}
return callQuery(parameterList);
});
} else {
return callQuery(parameterList);
}
},
getFieldsByAccountId: function(accountId, showDeleted) {
var callQuery = function(paramList) {
var query = 'SELECT ' + paramList.columns.join(", ") + ' FROM fields WHERE account_id = :account_id';
if (!showDeleted) {
query += ' AND archived_at IS NULL';
}
return internals.query(query, paramList, function(rows) {
return _.each(rows, function(row) {
if(row.options) {
row.options = JSON.parse(row.options);
}
row.required = !!row.required;
});
});
};
var columnList = ["uuid", "account_id", "shortcut_name", "display_name", "field_type", "required", "column_order", "options"];
var paramList = {'account_id': accountId};
if (showDeleted) {
columnList.push("archived_at");
}
_.extend(paramList, {'columns': columnList});
return callQuery(paramList);
}
};
Here is my test:
'use strict';
var assert = require('assert');
var sinon = require('sinon');
var Promise = require('bluebird');
var proxyquire = require('proxyquire');
var returnedValues = require('../../../return_values.js');
var fieldGateway = proxyquire('../../../../src/fields/lib/gateway', {});
describe('gateway', function () {
var accountId = 100;
var fieldId = 200;
var _query, sql, mockData, rows;
describe('createField', function() {
describe('is successful with a column order value', function () {
beforeEach(function() {
sql = 'INSERT into fields VALUES (:uuid, :accountId, :shortcutName, :displayName, :fieldType, :widgetType, :columnOrder, :options, :required, NULL)';
mockData = returnedValues.getFieldInputValues();
});
it("should only insert new field", function () {
_query = sinon.spy(function() { return Promise.resolve(); });
fieldGateway.initialize(_query);
fieldGateway.createField(fieldId, accountId, mockData);
mockData.accountId = accountId;
mockData.uuid = fieldId;
mockData.options = JSON.stringify(mockData.options);
assert.equal(sql, _query.getCall(0).args[0]);
assert.deepEqual(mockData, _query.getCall(0).args[1]);
});
it.only("_query should be called with the right sql statement and parameterList", function () {
_query = sinon.stub().returns(Promise.resolve(fieldId));
// _query.onCall(0).returns(Promise.resolve([{'MAX(column_order)': 10}]));
// _query.onCall(1).returns(Promise.resolve(fieldId));
fieldGateway.initialize(_query);
delete mockData.columnOrder;
fieldGateway.createField(fieldId, accountId, mockData);
console.log(_query.args);
assert.equal(sql, _query.getCall(0).args[0]);
fieldGateway.createField.restore();
});
});
});
});
The problem is that when the test runs, the only SQL query that runs is the SELECT statement. What should happen is one SQL statement runs, then an INSERT statement runs
This happens because bluebird is a true Promise/A+ compliant library. And by definition all chained promises must be run in a different execution tick. So only the first promise is executed synchronously (in same tick).
You should tell mocha to "wait" for the rest to act. You do this by specifying a done callback in your unit test and calling it accordingly when your promises finished their job
it.only("_query should be called with the right sql statement and parameterList", function (done) {
_query = sinon.stub().returns(Promise.resolve(fieldId));
fieldGateway.initialize(_query);
delete mockData.columnOrder;
fieldGateway.createField(fieldId, accountId, mockData)
.then(function(){
/// assertion code should be adjusted here
console.log(_query.args);
assert.equal(sql, _query.getCall(0).args[0]);
fieldGateway.createField.restore();
//tell Mocha we're done, it can stop waiting
done();
})
.catch(function(error) {
//in case promise chain was rejected unexpectedly
//gracefully fail the test
done(error);
};
});
Whenever you test your promise-returning functions you should always handle result in a .then
In my main.js, I have:
var example = require('./test');
example.speak('Hello world');
While in my test.js, I have:
module.exports = function() {
this.speak = function(str) {
str += ' < you typed.';
return str;
};
this.listen = function(str) {
return str;
};
};
What exactly am I doing wrong so that I can use browserify correctly with this?
You should either export an object:
module.exports = {
speak: function () {},
// etc
}
or use
var example = new require("./test")();
Is it possible to name a method dynamically?
Let us say:
Class.prototype[name] = function(param) {
console.log(name, param)
}
So if I do:
// will return `hello there`
class.hello('there')
// will return `hey there`
class.hey('there')
Is this possible to do?
I'm using the library zerorpc.
They have a syntax of
client.invoke("iter", 10, 20, 2, function(error, res, more) {
So I want to create a class to wrap their function so I can do something like:
client.iter(10,20,2 function(...
This is how I tried:
var zerorpc = require('zerorpc')
var util = require('util')
var EventEmitter = require('events').EventEmitter
var RPC = function () {
if (!(this instanceof RPC)) return new RPC()
this.rpc = new zerorpc.Client()
}
util.inherits(RPC, EventEmitter)
module.exports = RPC()
RPC.prototype.connect = function(config) {
this.con = this.rpc.connect('tcp://' + config.host + ':' + config.port)
}
// this is the idea
RPC.prototype[name] = function(params) {
this.rpc.invoke(name, params[0], params[1], params[2], function(error, res, more) { // ...
}
Saw this on gitbub gist.
Are you looking for proxies?
var obj = Proxy.create({
get: function(target, value) {
return function() {
console.log('called ' + value)
}
}
});
obj.hello(); // "called hello"
obj.world(); // "called world"
You have to use --harmony_proxies option to enable proxies in node.