I am trying to connect to a MySQL database in my Cucumber-JS stepDefinition file, using node-mysql, via a connection method defined in world.js. Unfortunately it will not connect and return my query results, nor can I get it to show me an error message that will help me figure out where I am going wrong.
I have used Cucumber-JVM in the past, but am new to JavaScript and node.js. I have created a standalone js file with the same method present (to mimic the world.js), and called that successfully from another test script (to mimic the stepDefinitions.js); it connects and returns the record happily, so this is probably down to my misunderstanding of context within JavaScript in general, or within the way Cucumber-JS uses world, perhaps...
stepDefinitons.js:
'use strict';
var ImportStepDefinitions = function() {
this.World = require('../support/world.js').World;
this.Given(/^I have a clean Magento database$/, function (callback) {
this.connectToDatabase();
//this.clearDatabase();
callback();
});
this.When(/^I import the test data file "([^"]*)"$/, function (testDataFile, callback) {
//this.importTestFile();
callback.pending();
});
this.Then(/^an attribute set is created called "([^"]*)"$/, function (attributeSetName, callback) {
//this.validateAttributeSet();
callback.pending();
});
};
module.exports = ImportStepDefinitions;
world.js:
'use strict';
var World = function World(callback) {
var mysql = require('mysql');
var host = 'localhost';
var user = 'user';
var password = 'password';
var database = 'magento';
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
database: database
});
this.connectToDatabase = function () {
connection.connect(function(err){
if(err) {
console.error("Connection error: " + err.stack);
return;
}
console.log("Connection state 1 = ", connection);
});
connection.query('SELECT * FROM admin_user', function (err, rows, fields) {
if (err) {
console.error("Query error: " + err.stack);
return;
}
console.log("ROWS ====== ", rows[0]);
recordDetail = rows[0];
});
console.log("Connection state 2 = ", connection);
connection.end();
};
this.clearDatabase = function(scriptName) {
//Run import script in sql so starting with a fresh magento database
};
this.importTestFile = function(testFileName) {
//Need to call import.php with file location
};
this.validateAttributeSet = function(attributeSetName) {
//Use magento object (?) to check attribute set exists as expected
};
callback();
};
module.exports.World = World;
When I execute the code I get nothing back from connection.connect(), neither error or log, no record is logged out from connection.query(), and connection at 'connection state 2 =' shows (right at the bottom) a _connectCalled value of true, but a state of disconnected and a threadId of null:
Connection state 2 = { domain:
{ domain: null,
_events: { error: [Function: handleScenarioException] },
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events: {},
_maxListeners: undefined,
config:
{ host: 'localhost',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'user',
password: 'password',
database: 'magento',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_socket:
{ _connecting: true,
_hadError: false,
_handle:
{ fd: -1,
reading: false,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0 },
_parent: null,
_host: 'localhost',
_readableState:
{ objectMode: false,
highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null,
resumeScheduled: true },
readable: false,
domain:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events:
{ end: [Object],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
data: [Function],
error: [Function],
connect: [Object],
timeout: [Object] },
_maxListeners: undefined,
_writableState:
{ objectMode: false,
highWaterMark: 16384,
needDrain: false,
ending: false,
ended: false,
finished: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false },
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 0,
_bytesDispatched: 0,
_pendingData: null,
_pendingEncoding: '',
_idleTimeout: 10000,
_idleNext: { _idleNext: [Circular], _idlePrev: [Circular] },
_idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] },
_idleStart: 2735419 },
_protocol:
{ domain:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
members: [],
id: 'domain-1437457225974' },
_events:
{ data: [Function],
end: [Object],
handshake: [Function],
unhandledError: [Function],
drain: [Function],
enqueue: [Function] },
_maxListeners: undefined,
readable: true,
writable: true,
_config:
{ host: 'localhost',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'user',
password: 'password',
database: 'magento',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshakeSequence:
{ domain: [Object],
_events: [Object],
_maxListeners: undefined,
_callback: [Object],
_callSite: [Error],
_ended: false,
_timeout: undefined,
_idleNext: null,
_idlePrev: null,
_idleStart: null,
_idleTimeout: undefined,
_repeat: null,
_config: [Object],
_handshakeInitializationPacket: null },
_handshaked: false,
_ended: false,
_destroyed: false,
_queue: [ [Object], [Object] ],
_handshakeInitializationPacket: null,
_parser:
{ _supportBigNumbers: false,
_buffer: <Buffer >,
_longPacketBuffers: [],
_offset: 0,
_packetEnd: null,
_packetHeader: null,
_packetOffset: null,
_onError: [Function],
_onPacket: [Function],
_nextPacketNumber: 0,
_encoding: 'utf-8',
_paused: false } },
_connectCalled: true,
state: 'disconnected',
threadId: null }
Ok, I believe I have found a solution, so posting here for anyone else struggling in a similar manner. Please feel free to post a better explanation of why and what is happening here if you have one!
I had not implemented the callback properly, as detailed by the cucumber.js documentation; I need to pass that to the function being called, and use it to signify when that called function has completed:
StepDefinitions.js:
...
this.Given(/^I have a clean Magento database$/, function (callback) {
//callback passed into function
this.connectToDatabase(callback);
...
world.js:
...
//callback now passed into function
this.connectToDatabase = function(callback) {
var host = 'localhost';
var user = 'user';
var password = 'password';
var database = 'magento';
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
database: database
});
connection.connect(function(err){
if(err) {
console.error("Connection error: " + err.stack);
return;
}
});
connection.query('SELECT * FROM admin_user', function (err, rows) {
if (err) {
console.error("Query error: " + err.stack);
} else {
console.log(rows[0]);
}
});
/*callback used to signify end of function, ensuring all actions are
actually completed before the rest of the scenario steps are completed
by cucumber.js*/
connection.end(callback);
};
....